2011-03-21 134 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/> 
}); 
相关问题