jQuery 在回调中获取源元素

标签 jquery function jquery-selectors callback jquery-callback

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

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

最佳答案

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

要在内部 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();
    });    
});

关于jQuery 在回调中获取源元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195142/

相关文章:

javascript - 代码块内定义的内部函数的语义是什么?

javascript - 如何更改替换功能中的所有单词

jquery - 需要 jQuery 选择器来将 <ul> 悬停在 <li> 中

jquery - 在 ul 内的 ul 内选择 li

javascript - 如何注入(inject) jQuery 并在同一个书签中使用它?

javascript - 我想使用 Javascript Replace() 添加 html 标签(但它以字符串形式返回它们)

javascript - jquery 中的控件不返回函数

jquery - 如何删除没有内部元素的div

javascript - 最后一次按键后 1.6 秒运行 js

jquery - jQuery 数据方法的返回值不会转换为 Number