2013-10-03 26 views
2

下面的代碼中的「this」和「element」是指什麼情況而不是選擇器?

$("a.tag") 
    .each(
     function (index, element) { 
      console.log("'this' is " + this); 
      console.log("'element' is " + element); 
     } 
    ) 

產生以下多次有元素:

'this' is file:///C:/Projects/PlaceTag/PlaceTag/default.html# default.html:50 
'element' is file:///C:/Projects/PlaceTag/PlaceTag/default.html# 
+3

有趣了,從來沒有看到過:http://jsfiddle.net/nYHfb/ –

+0

@JasonP同樣的現象被提及[這裏](http://stackoverflow.com/questions/3363848/javascript -this-keyword-returning-href-attribute-rather-than-object-on-anchor) – matewka

+0

Try console.log(this === el); – CodeGroover

回答

6

兩個thiselement總是指的DOM元素在.each()回調。

您的代碼通過+級聯運算符將DOM元素強制轉換爲字符串。
這將返回元素的href屬性。

相反,你可以對象本身傳遞給log()

console.log("'this' is ", this); 
+0

不應該在[[object Object]中使用強制字符串而不是頁面URL嗎? –

+1

@FrédéricHamidi:'HTMLAnchorElement'有它自己的'toString()'。 – SLaks

+0

當然。感謝您的回覆:) –

0

您使用。每任何時候,你的環境的變化,因此「本」的變化。簡單的解決方案是添加對「this」的引用。

var self = this; 
$("a.tag") 
.each(
    function (index, element) { 
     console.log("'self' is " + self); 
     console.log("'this' is " + this); 
     console.log("'element' is " + element); 
    } 
) 
+1

這與他想要的相反。 – SLaks

+0

這仍然是一個寶貴的見解。謝謝您的回答。 – Metaphor