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

以上不起作用,因为$(this)回调中不再处于正确的范围内。如何将我的原始源元素传递给回调?

4

3 回答 3

7

实际上你的代码应该可以工作。

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

$('.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();
    });    
});
于 2010-07-07T13:33:29.390 回答
2
$('.myElem').live('click', function() { 
    var $this = $(this);
    $this.hide(500, function() { 
        $this.siblings('.myOtherElem').show(); 
    }); 
}); 
于 2010-07-07T13:31:56.300 回答
0
$('.myElem').live('click', function() {
    $(this).hide(500);
    $(this).siblings('.myOtherElem').show();
});
于 2010-07-07T13:35:54.877 回答