jQuery AJAX$.post无法使用.click()方法

jQuery AJAX $.post not working with .click() method

本文关键字:click 方法 AJAX post jQuery      更新时间:2023-09-30

我的ajax请求有点困难。$.post方法似乎根本不起作用,没有发送任何请求。萤火虫也没什么表现。

我可以让这个工作:

   $('.comment-remove').click(function (evt) {
        evt.preventDefault();
        var sure = confirm('Are you sure your want to remove your comment from this thread?');
        if(sure) {              
            var comment_id = $(this).attr('id');
            alert(member_id);
        }
    });

但不是这个:

   $('.comment-remove').click(function (evt) {
        evt.preventDefault();
        var sure = confirm('Are you sure your want to remove your comment from this thread?');
        if(sure) {
            var comment_id = $(this).attr('id');
            $.post('comment.php', { comment_id: comment_id }, function(data) {
                if (data === 'success') {
                    alert(data);
                } else {
                    alert('Unable to remove comment at this time.');
                }
            }
        }
    });

HTML是:

<a class="comment-remove" id="<?php echo $comment_id; ?>">Remove my comment</a>

应该是:

$.post('comment.php', { comment_id: comment_id }, function(data) {
  if (data === 'success') {
    alert(data);
  } else {
    alert('Unable to remove comment at this time.');
  }
})

看到我添加的额外)了吗?它在开始时与$.post(中的(相匹配。你错过了,这总是很容易做到的。你的控制台应该能够告诉你这类事情。

您的post调用缺少一个右括号。试试这个:

    $('.comment-remove').click(function (evt) {
        evt.preventDefault();
        var sure = confirm('Are you sure your want to remove your comment from this thread?');
        if(sure) {
            var comment_id = $(this).attr('id');
            $.post('comment.php', { comment_id: comment_id }, function(data) {
                if (data === 'success') {
                    alert(data);
                } else {
                    alert('Unable to remove comment at this time.');
                }
            })
        }
    });