jQuery在回调中获取源元素

时间:2010-07-07 13:29:16

标签: jquery function jquery-selectors callback jquery-callback

$('.myElem').live('click', function() {
    $(this).hide(500, function() {
        $(this).siblings('.myOtherElem').show();
    });
});

上述方法无效,因为$(this)在回调中的范围不再正确。如何将原始源元素传递给回调?

3 个答案:

答案 0 :(得分:7)

实际上你的代码应该有用。

要在内部javascript方法中访问this,您可以将引用存储在外部方法范围中:

$('.myElem').on('click', function() {

   var myElem = this;    
    $(this).hide(500, function() {
        $(myElem).siblings('.myOtherElem').show();
    });

});

然而,在大多数jQuery方法中,this指的是使用的选择器或元素:

$('.myElem').on('click', function() {
    // This refers to the clicked element
    $(this).hide(500, function() {
       // This refers to the clicked element as well 
       $(this).siblings('.myOtherElem').show();
    });    
});

答案 1 :(得分:2)

$('.myElem').live('click', function() { 
    var $this = $(this);
    $this.hide(500, function() { 
        $this.siblings('.myOtherElem').show(); 
    }); 
}); 

答案 2 :(得分:0)

$('.myElem').live('click', function() {
    $(this).hide(500);
    $(this).siblings('.myOtherElem').show();
});