简体   繁体   中英

Javascript/Jquery Single event target delegation

I realized event.target redundancy could cause a lot of problems in the future when they are binded with another event in the next level.

For example, when i have an Div element inside another.

<div id='div1'>
  <div id='div2>
  </div>
</div>

I use the follow Jquery code to bind an event.

$('div').bind('click', function(event){
   alert(event.target.id)
}

There are two alert boxes instead of one. I understand the concept of why is because there are 2 divs I am clicking.

Of course the problem in a deeper level is that when I am trying to bind an event after this event accordingly with the event.target, it binds x2 so on and so forth.

Is it possible to get rid of the event binding on the outside div and only capture the inside.

Thanks in advance.

You can prevent the event from bubbling using event.stopPropgation() like this:

$('div').bind('click', function(event){
  alert(event.target.id);
  event.stopPropagation();
});

You can give it a try here . This will "trap" the click on the first <div> that gets it, and won't let it propagate up to any parents.

I think you just need to select the inside div in your bind call:

$('div:eq(0)').bind('click', function(event){
   alert(event.target.id)
}

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