jQuery在回调中获取源元素

fea*_*net 4 jquery function callback jquery-selectors jquery-callback

$('.myElem').live('click', function() {
    $(this).hide(500, function() {
        $(this).siblings('.myOtherElem').show();
    });
});
Run Code Online (Sandbox Code Playgroud)

以上操作无效,因为$(this)回调中的范围不再正确.如何将原始源元素传递给回调?

jan*_*mon 7

实际上你的代码应该工作.

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

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

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

});
Run Code Online (Sandbox Code Playgroud)

但是在大多数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();
    });    
});
Run Code Online (Sandbox Code Playgroud)