Jquery简单的功能

时间:2011-04-23 17:25:24

标签: javascript jquery ajax

此代码的目的是使用AJAX删除注释。该函数调用如下:

DeleteComment(166);

运行的代码是:

// Each delete button
function DeleteComment(CommentID) {

    $.ajax({
        url: AJAXURL + "?action=del&id=" + CommentID,
        success: function (data) {

            // Parse the data
            if (data.substring(0, 1) == "1") {

                $('#cid' + CommentID).hide();

            } else {
                alert(data.substring(2, data.length));
            }
        }
    });

}

$('#cid' + CommentID).hide();行永远不会触发,因为CommentID未被保留,我是Jquery的新手,有人可以告诉我如何更改此内容,以便在保留注释ID时保留ajax的成功被称为?

2 个答案:

答案 0 :(得分:1)

$('#cid' + CommentID).hide();放在$.ajax({之前,然后将$('#cid' + CommentID).show();添加到您的其他条件中。

首先隐藏它,然后在删除失败时重新显示它......

不是最优雅的解决方案,而是来自你所处位置的阻力最小的路径。

答案 1 :(得分:1)

你能发布更多周围的代码吗?因此,您的代码看起来应该可以工作。但我看到了一个麻烦的评论:// Each delete button。将DeleteComment函数绑定到按钮的方式不能像您假设的那样工作。

请改为尝试:

// Iterate over each delete button.  
// The .each(...) provides you a function, a.k.a. local scope, for each button.
$(".deleteButtons").each(function (idx, el) {

    // This is very important: you must create a local variable to hold the ID.
    // How to get the ID is up to you.
    var id = getTheCorrespondingCommentId(idx, el); 

    // Now you can safely pass the local variable to the DeleteComment function:
    $(el).click(function() { DeleteComment(id); });
});