In view of the above jQuery on...">

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
jquery
source share
6 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
source share

Just use $(this) in the callback function to find out which item was fired.

 $('.test').click( function() { alert( $(this).attr('id') ); }); 
+2
source share

I 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
source share

Alternatively, 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); }); 

Jsfiddle

0
source share

HTML

  <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
source share

Maybe something like:

 document.getElementById("test-1000").onclick = function(){}); 

You cannot use an element until it is defined.

-2
source share

All Articles