7

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?

1
  • the event passed into the click event will hold a reference to the actual element that was clicked, so you can easily identify it by that method... normally [ .click(function(evt){evt.target}) ] Commented Oct 15, 2013 at 3:08

6 Answers 6

10

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
})
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

0

I prefer to go with data attribute and class approach

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

Comments

0

Alternatively, if you don't want or can't modify your html, you can use jquery "starts-with" selector.

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

$("[id^='test']").on('click', function(){
    console.log(this.id);
});

JsFiddle

Comments

0

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

Comments

-2

Maybe something like:

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

You can not use the element before it is defined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.