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

以上不起作用,因爲$(this)在回調中不再處於正確的範圍內。如何將我的原始源元素傳遞給回調函數?jQuery在回調中獲取源元素

回答

7

其實你的代碼應該工作。

到內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(); 
    });  
}); 
2
$('.myElem').live('click', function() { 
    var $this = $(this); 
    $this.hide(500, function() { 
     $this.siblings('.myOtherElem').show(); 
    }); 
}); 
0
$('.myElem').live('click', function() { 
    $(this).hide(500); 
    $(this).siblings('.myOtherElem').show(); 
}); 
+0

這不會完成同樣的事情。將'.show()'調用放在回調函數中可以確保直到'.hide()'動畫完成後它纔會發生。答案中的代碼將導致它們幾乎同時發生。 – 2010-07-07 13:38:30

+0

你可以通過使用'delay'來實現:'.delay(500).show(1)'但是使用'show'回調是更好的解決方案。 – jantimon 2010-07-07 13:42:17