2011-03-21 63 views
3

哎, 看看這個代碼:我是誰或我如何知道我正在處理的元素?

$("li,p").click(function(){ 

    // how do I perform a test, and know wich Element it is ? 

    if(/* I'm a <li/> */) 
     // Do this for the <li/> 

    if(/* I'm a <p/> */) 
     // Do this for the <p/> 
}) 

謝謝你們^^

+1

爲何使用相同的處理程序裏和P,如果你需要爲每個做不同的事情? – Belinda 2011-03-21 14:01:12

+0

我有相同的指令(很多實際)來執行他們兩個。但其他人有一些差異 – 2011-03-21 14:04:28

回答

6

一種選擇是使用is()方法:

$("li,p").click(function(){ 

    // how do I do I perform a test, on wich Element it is ? 

    if($(this).is('li')) 
     // Do this for the <li/> 

    if($(this).is('p')) 
     // Do this for the <p/> 
}) 
+1

哦,天哪,你比我快。 – 2011-03-21 13:58:49

+0

實際上,我應該先看看API,然後再問:P,但是謝謝你們,你們很有幫助 – 2011-03-21 14:00:44

3

您正在尋找this.nodeName

你也可以寫

if (jQuery.nodeName(this, 'p')) 
1

Live Demo

$("li,p").click(function(){ 
    if(this.tagName.toLowerCase() == "p"){ 
     alert("PP!"); 
    }else if(this.tagName.toLowerCase() == "li"){ 
     alert("list!"); 
    } 
}) 
1

使用is()功能

$("li,p").click(function(){   

    if($(this).is('li'))   
     // Do this for the <li/>  
    if($(this).is('p'))   
     // Do this for the <p/> 
}); 
相關問題