Who am I or How do I know which Element I'm dealing with?
Inside the f开发者_开发问答ollowing code how do I perform a test, and know which element was clicked?
$("li,p").click(function(){
// how do I perform a test, and know which Element it is?
if( /* I'm a <li/> */ )
// Do this for the <li/>
if( /* I'm a <p/> */ )
// Do this for the <p/>
})
One option would be to use the is() method:
$("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/>
})
You're looking for this.nodeName
.
You can also write
if (jQuery.nodeName(this, 'p'))
Live Demo
$("li,p").click(function(){
if(this.tagName.toLowerCase() == "p"){
alert("PP!");
}else if(this.tagName.toLowerCase() == "li"){
alert("list!");
}
})
Use the is()
function
$("li,p").click(function(){
if( $(this).is('li') )
// Do this for the <li/>
if( $(this).is('p') )
// Do this for the <p/>
});
精彩评论