$('.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/