Javascript / Jquery单事件目标委派 [英] Javascript/Jquery Single event target delegation

查看:107
本文介绍了Javascript / Jquery单事件目标委派的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到event.target冗余可能在将来与另一个事件绑定在一个新的级别时会导致很多问题。



例如,当我有另一个Div元素时。

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

我使用以下Jquery代码绑定事件。

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

有两个提示框而不是一个
我理解为什么是这样的概念,因为我点击了两个div。



当然,更深层次的问题是当我试图绑定一个事件在事件相应的event.target之后,它绑定x2等等。



是否可以摆脱外部div上的事件绑定,只有捕获内部。



提前感谢

解决方案

防止冒泡使用 event.stopPropgation() 这样:


$ b $($'$'$'$''''''''''''''''''' b alert(event.target.id);
event.stopPropagation();
});

你可以试试这里。这将捕获获得它的第一个< div> 上的点击,不会让它传播到任何父母。


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.

这篇关于Javascript / Jquery单事件目标委派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆