javascript - 为什么这个 jquery 代码没有删除 li 列表项?

标签 javascript jquery html

$('#list li a').on('click', function(e) {
    var user_id = this.parentNode.id.replace('list_', '');
    var id = 'id=' + user_id;
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "xxx.php",
        data: id,
        success: function() {
            $(this).parent().hide(); //the problem is here 
            $('.updateNumber').html(function() {
                return parseInt($(this).text(), 10) + 1;
            });
        }
    });
});

我认为在 ajax 调用之后,由于 (THIS) 选择器,它无法重新识别 li 列表,它没有正确引用它,感谢您的帮助

最佳答案

您是正确的,在 Ajax 回调中 this 不是单击的 anchor 。以下内容应该有效:

    $('#list li a').on('click', function(e) {

        var user_id = this.parentNode.id.replace('list_', '');
        var id = 'id=' + user_id;
        e.preventDefault();

        var $a = $(this);

        $.ajax({
        type: "POST",
        url: "xxx.php",
        data: id,
        success: function(){
            $a.parent().hide();
            $('.updateNumber').html(function(){
               return parseInt($(this).text(),10)+1;
            });
        });
    });

$.ajax() 调用之外保存对单击链接的引用。回调函数可以访问其包含范围内的变量。

关于javascript - 为什么这个 jquery 代码没有删除 li 列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627166/

相关文章:

javascript - 当不同文件中存在测试时,如何在 jasmine 中对测试套件进行分组?

jquery - jQuery 中的垂直视差

javascript - 将图像相互堆叠问题

javascript - 带有 Geddy : Does geddy. string.uuid(x) 的 Node.js 确保字符串是唯一的?

javascript - 在同一页面中导航 anchor 标记时关闭左滑菜单?

jquery - CSS标准化文本背景

javascript - 如何浏览一个javascript对象

java - JApplet在HTML页面中运行失败

html - 打开标志性 Bootstrap 不起作用

javascript - 如何在javascript中找到第一个未定义的数组元素,并填充它?