2013-09-16 64 views
10

簡單問題:jQuery選擇參考自我

如何我指的是自我,而無需使用$.each()例如,當我想設置html()到自己的屬性?

$('*[rel]').html($(this).attr('rel')); // nope 
$('*[rel]').html($(self).attr('rel')); // nah 
$('*[rel]').html($(sender).attr('rel')); // undefined 
$('*[rel]').html($(target).attr('rel')); // still undefined 
$('*[rel]').html($(???).attr('rel')); // this isn't even correct syntax 
$('*[rel]').html($(beer).attr('rel')); // well that would be tasty 
$('*[rel]').html($(woman).attr('rel')); // not in this life 
$('*[rel]').html($(god help me!).attr('rel')); // He probably doesn't even know how to use a computer 
$('*[rel]').html($(i give up).attr('rel')); // unexpected... o'rly? 
+4

_He可能甚至不知道如何使用computer_ :)如果只, – undefined

+1

投票彌補這個問題本身它的幽默... :) – TheCuBeMan

回答

12

You can pass a function instead of a a string.

$('[rel]').html(function() { 
    return $(this).attr('rel'); 
}); 

之所以所有的例子不工作是因爲在每種情況下你的代碼執行的選擇進行了評估之前很久。這是你真正需要理解的東西 - 當涉及回調時,它更加相關。對於AJAX或定時器:當你把代碼放在某個地方時,它就會在這個時候執行。所以foo(some code here)總是執行功能參數的一部分的代碼,無論foo做什麼。避免這種情況的唯一原因是傳遞一個包含此代碼的函數 - 即對函數表達式進行評估(計算出可調用函數)。然後,實際的函數(顯然需要期望可調用而不是簡單的值)可以在適當的時候調用傳遞的函數。

+0

確定。我明白,js是基於回調的,但是很久以前,在遙遠的一片土地上,肯定會住着一個美麗的年輕女孩......是的,她有一臺電腦,其中舊版,舊版j,j,jQuery'sender'或'self'工作。但我可能對女孩錯了,年輕的時候,每個女孩都很漂亮。 –

+0

是的,我認爲那個女孩讓你覺得奇怪的東西 - 從技術上說你不可能以這種方式工作。 – ThiefMaster