2012-01-06 36 views
8

找出$(this)目前在jQuery中等效的最佳方式是什麼?

例如沒有太大的幫助。

我問的原因是一段代碼目前沒有做它應該做的事情,我已經將代碼移到一個函數中。

下面的摘錄現在在一個函數中,而$(this)現在似乎指的是DOMWindow。

if($(this).hasClass('open')) 
    { 
    alert('I should be closed'); 
    $(this).removeClass('open').addClass('closed'); 
    $(this).parents('article').css('border', '1px solid red').animate({'width': '212px'}, 100, "linear", function() { 
    run_masonry(); 
    }); 
    } 
    else 
    { 
    alert('I should be open'); 
    $(this).removeClass('closed').addClass('open'); 
    $(this).parents('article').css('border', '1px solid blue').animate({'width': '646px'}, 100, "linear", function() { 
    run_masonry(); 
    }); 
} 

我該如何保持$(this)是原始點擊元素?

回答

22

什麼是最好的方式來找出什麼$(this)當前等於jQuery?

通過它登錄到自己喜歡的JavaScript調試工具的控制檯(如FireBug或Chrome開發人員例如工具欄):

console.log($(this)); 

將返回一個jQuery包裝的對象。如果您想了解更多關於原生對象,你可以使用:

console.log(this); 

如果你正在做的JavaScript開發,你應該使用一個JavaScript調試工具。 alert不是這樣的工具。


現在你已經更新了一些代碼源你的問題好像你是在全球範圍內使用$(this)。然後它將引用window對象。如果你希望它是指一些點擊的元素或東西,你必須首先訂閱。點擊事件:

$('.someSelector').click(function() { 
    // here $(this) will refer to the original element that was clicked. 
}); 

,或者如果你想這個外部化的代碼在一個單獨的功能:

function foo() { 
    // here $(this) will refer to the original element that was clicked. 
} 

$('.someSelector').click(foo); 

或:

function foo(element) { 
    // here $(element) will refer to the original element that was clicked. 
} 

$('.someSelector').click(function() { 
    foo(this); 
}); 
+0

反正是有縮小它返回大量的數據 – 2012-01-06 10:33:39

+0

@CraigWard,是的,使用'的console.log(本);'只次登錄? e本地對象而不是'$(this)'。 – 2012-01-06 10:34:49

+0

@CraigWard你想把它縮小到什麼程度?我希望它是'$(this).attributesThatIWantToSee()' – Connell 2012-01-06 10:36:43

1

隨着移動碼成一個函數的代碼改變通常的範圍。所以「this」將不再引用原始對象,而是引用新對象(或全局「窗口」對象)。如果您向我們顯示您的代碼,我們將能夠確定問題。

+0

聽起來像是這個問題。它返回DOMWindow。有沒有辦法在函數中保留$(this)? – 2012-01-06 10:38:23

+0

很多方法,但這取決於你在做什麼錯... – 2012-01-06 10:44:17

+0

我已經更新了問題,包括一些代碼 – 2012-01-06 10:48:45

0

我懷疑你做這樣的事情:

$('#element').click(function() { 
    clickHandler(); 
}); 

在這種情況下clickHandler將在Window對象的上下文中調用。爲了保持正確的上下文只是改變你的代碼:

$('#element').click(clickHandler); 
0

如果要檢查什麼正在傳來傳去,你可以使用我的版本或prinzhorn的jquerylog的版本。它應該幫助您一步找出一步發生了什麼:

http://www.jquerylog.com/https://github.com/fmsf/jQueryLog

對於調用,比如:

$("#foo").parents(".t1").next().prev().parent().find(".t2:last .t4:last").text("test"); 

你會得到這樣的輸出(標識在每一步DIV :

$('#foo'): [<div id="foo" class="t3"></div>] 
    parents('.t1'): [ <div class="t1">…</div> ] 
     next(undefined): [ <div class="t1">…</div> ] 
      prev(undefined): [ <div class="t1">…</div> ] 
       parent(undefined): [ <body>…</body> ] 
        find('.t2:last .t4:last'): [<div class="t4">teste</div>]