开发者

Detect a click on DIVs with unpredictable IDs in jQuery

开发者 https://www.devze.com 2023-03-29 00:36 出处:网络
I have several div tags and I\'m trying to detect which one clicked. Each result has a unique title, but the same id. How do I use .click() to know which one was cl开发者_JS百科icked so I can get it\'

I have several div tags and I'm trying to detect which one clicked. Each result has a unique title, but the same id. How do I use .click() to know which one was cl开发者_JS百科icked so I can get it's ID and use it?


$('div').click(function(){
    alert(this.id);
});


This one checks if the div has img as a child and then triggers the click.

$('div:has(img)').click(function(){
    // do something
});


You can add a listener that captures clicks using the parent > child methods. For instance:

<div id="parent">
   <div id="result" title="df45fds46"></div>
   <div id="result" title="48df6sfsd"></div>
</div>

Then on the javascript:

$("#parent div").click(function(){
   console.log(this.attr('title')); // or $(this).attr('title'), i'm not quite sure
});


Try this -

$('div').click(function(e){
    e.stopPropagation();
    alert("Id: " + event.toElement.id);
    alert("Title: " + event.toElement.title)
});

Try This

0

精彩评论

暂无评论...
验证码 换一张
取 消