$('.myElem').live('click', function() {
$(this).hide(500, function() {
$(this).siblings('.myOtherElem').show();
});
});
以上不起作用,因为$(this)
在回调中不再处于正确的范围内。如何将我的原始源元素传递给回调函数?jQuery在回调中获取源元素
$('.myElem').live('click', function() {
$(this).hide(500, function() {
$(this).siblings('.myOtherElem').show();
});
});
以上不起作用,因为$(this)
在回调中不再处于正确的范围内。如何将我的原始源元素传递给回调函数?jQuery在回调中获取源元素
其实你的代码应该工作。
到内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();
});
});
$('.myElem').live('click', function() {
var $this = $(this);
$this.hide(500, function() {
$this.siblings('.myOtherElem').show();
});
});
$('.myElem').live('click', function() {
$(this).hide(500);
$(this).siblings('.myOtherElem').show();
});
这不会完成同样的事情。将'.show()'调用放在回调函数中可以确保直到'.hide()'动画完成后它才会发生。答案中的代码将导致它们几乎同时发生。 – 2010-07-07 13:38:30
你可以通过使用'delay'来实现:'.delay(500).show(1)'但是使用'show'回调是更好的解决方案。 – jantimon 2010-07-07 13:42:17