简体   繁体   中英

How to alert the id of nested div without alerting the id of its parent?

I want to alert the id of the div when I click on it. The code works fine but it also alerts the id of the parent div. How can I avoid that?

Here's the code: JSBin Link

<div id ="parentDiv">
  <div id ="child1"></div>
  <div id ="child2"></div>
</div>

JQuery Code:

$(document).ready(function(){
  $('div').click(function(){
   var index = $(this).attr("id");
   alert(index);
  });
});

use e.stopPropagation()

$('div').click(function(e){
   e.stopPropagation();
   var index = $(this).attr("id");
   alert(index);
});

Demo ---> http://jsbin.com/osafuw/1/edit

You can use children() as well

$(document).ready(function(){
    $('div').children().click(function(){
    var index = $(this).attr("id");
    alert(index);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM