Jquery multi click event?
There are two divs on my page.
<div id="test-1000"></div> <div id="test-1111"></div> In view of the above jQuery one click event event:
$('#test-1000').click(function(){}); But how to reach two divs with the same event above, click to track events, and how to distinguish a div which is a click event?
+7
Justin zhang
source share6 answers
I use a generic class attribute to group all target elements
<div class="test" id="test-1000" data-id="1000"></div> <div class="test" id="test-1111" data-id="1111"></div> then
$('.test').click(function(){ //here this.id will give the clicked div id and this will refer the clicked dom element //$(this).data('id') will give 1000/1111 }) +10
Arun P Johny
source shareJust use $(this) in the callback function to find out which item was fired.
$('.test').click( function() { alert( $(this).attr('id') ); }); +2
jbarnett
source shareI prefer to use the data and class attribute
HTML code
<div class="test" data="0000">1</div> <div class="test" data="1111">2</div> Js
$('.test').click(function(){ alert($(this).attr("data")); }); sample demo
0
Kasma
source shareAlternatively, if you do not want or cannot change your html, you can use the jquery "start-with" selector .
<div id="test-1000"></div> <div id="test-1111"></div> $("[id^='test']").on('click', function(){ console.log(this.id); }); 0
Romain meresse
source shareHTML
<div class="test" id="test-1000" data-id="1000"></div> <div class="test" id="test-1111" data-id="1111"></div> Js
$('.test').click(function(){ //here this.id will give the clicked div id and this will refer the clicked dom element //$(this).data('id') will give 1000/1111 }); 0
user2882854
source shareMaybe something like:
document.getElementById("test-1000").onclick = function(){}); You cannot use an element until it is defined.
-2
jarmerson
source share