Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery multiple click event?

Tags:

jquery

There are two div in my page.

<div id="test-1000"></div>
<div id="test-1111"></div>

In view of above single click event source jQuery is:

$('#test-1000').click(function(){});

But how to achieve two div with a similar to the above statement click events to be monitored are, and how to distinguish between div, which is the click event?

like image 414
Justin Zhang Avatar asked Oct 15 '13 02:10

Justin Zhang


People also ask

Why is this jQuery Ajax click event firing multiple times?

This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.

Can we use two events together in jQuery?

The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.

What is on () in jQuery?

The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.

What is unbind in jQuery?

jQuery unbind() Method The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.


2 Answers

I'll use a common class attribute to group all the 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
})
like image 173
Arun P Johny Avatar answered Oct 07 '22 15:10

Arun P Johny


Just use $(this) in the callback function to know 'which' element the event fired on.

$('.test').click( function() {
    alert( $(this).attr('id') );
});
like image 32
jbarnett Avatar answered Oct 07 '22 13:10

jbarnett