2011-12-22 95 views
31

我想要做什麼:比較 'e.target' 到jQuery對象

(clickedObject === someDiv) //returns true or false 

我試了一下

($(e.target) === $('.selector')); //returns a false negative. 

我的解決方法

($(e.target).attr('class') === $('.selector').attr('class')); //works as intended, not so clean though. 

什麼是正確的方式比較我點擊的對象在DOM中的對象?

回答

32

要檢查e.target是否有此類,您可以使用hasClass函數。

if ($(e.target).hasClass("selector")) 

或者,如果你真的要比較的對象,注意jQuery選擇返回項目的集合,所以我想你會想

if (e.target === $('.selector')[0]) 
+0

我喜歡這個答案,因爲它描述了爲什麼我的做法沒有奏效。 jQuery返回一組項目。 – dubbelj 2011-12-22 15:57:22

+0

@dubbelj - 酷 - 很高興它幫助:) – 2011-12-22 15:58:16

29

你靠近。使用.is()代替:

if($(e.target).is('.selector')) { 
    // Your code 
} 

這裏的技巧是,你在一個jQuery對象包裝e.target允許它訪問所有有用的jQuery方法。

如果你只是看到e.target是否具有一定的階級,試圖取代使用.hasClass().is()

if($(e.target).hasClass('selector')) { 
    // Your code 
} 

這兩種方法的工作原理,但.hasClass()是作爲對代碼做什麼更清晰一點,和比使用.is()

+0

+1只是輸入相同的東西。 – 2011-12-22 15:50:22

+2

+1 - boom - 'nice answer'徽章:) – 2011-12-22 15:56:54

+2

@ 32bitkid我很抱歉;-)我曾經發生過這麼多次! – Bojangles 2011-12-22 15:58:50

0

更快,如果你想要的元素相匹配的事件連接到你可以使用$(this),或者如果你想找到哪個元素觸發事件使用$(event.target)

下面是這兩個例子。

http://jsfiddle.net/Phunky/TbJef/

除非你使用事件委託這些將是相同的,雖然如果有相同的元素。

0

顯然使用.is()函數是這裏最好的解決方案。

如果你發現自己在做這樣的比較,試圖檢查它是否可以使用嵌入jQuery的機制是這樣的:

$(element).on("click", ".selector", function() { 
    alert("clicked"); 
}); 

.on()方法第二個參數是目標選擇。當使用這種結構時(閱讀更多:http://api.jquery.com/on/#direct-and-delegated-events)將不需要進行任何額外的比較。