删除元素的问题

时间:2011-09-23 22:39:20

标签: jquery

我不知道为什么这样做:

 $('.deleteQuestion').live('click', function(){
        $.ajax({
            type: 'GET',
            url: '/delete_question/' + $(this).attr('name') + '/',
            success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove()                            
        });      
    });

但这不起作用:

 $('.deleteQuestion').live('click', function(){
        $.ajax({
            type: 'GET',
            url: '/delete_question/' + $(this).attr('name') + '/',
            success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();}                            }
        });      
    });

有人知道吗?

4 个答案:

答案 0 :(得分:3)

成功回调不会在点击处理程序执行的同一this上运行。将其保存在变量中:

$('.deleteQuestion').live('click', function(){
    var element = $(this);
    $.ajax({
         type: 'GET',
         url: '/delete_question/' + $(this).attr('name') + '/',
         success: function(){ //this has to be a function, not a jQuery chain.
              $('[what="question"][name="' + element.attr('name') + '"]').remove();}
         }
    });      
});

答案 1 :(得分:2)

在第一个版本中$(this).attr('name')会立即评估。

在第二个版本中this没有指向当前元素,因为它仅在回调函数执行时被评估,这是在不同的上下文中 - 因此它将无法正常工作。

答案 2 :(得分:2)

我认为在这种情况下,两者都没有按你的意愿工作。

在第一个版本中,您有以下内容:

success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove()

一旦到达线路就会执行此操作,而不是成功回调。

在第二个版本中,您将在回调中丢失此内容:

success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();}

此外,看起来你还有一个额外的支撑。

remove();}                            }

尝试以下方法:

$('.deleteQuestion').live('click', function(){
        var self = this;
        $.ajax({
            type: 'GET',
            url: '/delete_question/' + $(this).attr('name') + '/',
            success: function(){$('[what="question"][name="' + $(self).attr('name') + '"]').remove();}
        });      
    });

答案 3 :(得分:2)

this并未指向成功函数中的内容。试试这个:

$('.deleteQuestion').live('click', function() {
    var that = this;
    $.ajax({
        type: 'GET',
        url: '/delete_question/' + $(this).attr('name') + '/',
        success: function() {
            $('[what="question"][name="' + $(that).attr('name') + '"]').remove();
        }
    });
});