Detect a click on DIVs with unpredictable IDs in jQuery
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
精彩评论