$('.myElem').live('click', function() {
$(this).hide(500, function() {
$(this).siblings('.myOtherElem').show();
});
});
上記は$(this)
、コールバックで正しいスコープにないため、機能しません。元のソース要素をコールバックに渡すにはどうすればよいですか?
$('.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();
});
});
$('.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();
});