javascript addEventListener而不选择子级 [英] javascript addEventListener without selecting children

查看:66
本文介绍了javascript addEventListener而不选择子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要仅将javascript用于该项目.抱歉,没有jQuery(我也感到羞愧).

I need to use javascript only for this project. Sorry, no jQuery (I feel ashamed as well).

我正在将addEventListener添加到div. 问题"是它也适用于所有子级.

I am adding an addEventListener to a div. "Problem" is that it applies to all its children, too.

有没有一种方法可以避免这种情况,并且让侦听器仅针对该div工作?

Is there a way to avoid this, and have the listener work only for that div?

预先感谢.

我的代码如下:

document.getElementById(myObj.id).addEventListener("mousedown", myObjDown, false);

function myObjDown() {
  //do stuff here
}

推荐答案

您可以通过在回调中读取event.target来判断事件实际触发了哪个元素.

You can tell which element the event actually fired on by reading event.target in your callback.

var el = ...
el.addEventListener('click', function(event){
  if (el !== event.target) return;

  // Do your stuff.

}, false);

另一种选择是将处理程序绑定到子元素,以防止事件到达父处理程序,但这需要更多工作,并且可能会将事件隐藏在实际上可能正在父级之上侦听它们的事物中.

The other option would be to have handlers bound to the child elements to prevent the event from reaching the parent handler, but that is more work and potentially hides events from things that might actually be listening for them above the parent.

给出示例代码,您应该可以做到这一点.

Given your example code, you should be able to do this.

var el = document.getElementById(myObj.id);
el.addEventListener("mousedown", myObjDown, false);

function myObjDown(event) {
  if (el !== event.target) return;

  //do stuff here
}

还要注意,请记住,如果这在IE< IE上不起作用,则没有任何建议. 9,因为不支持addEventListener.

Also as a general note, keep in mind that none if this will work on IE < 9 because addEventListener is not supported on those.

这篇关于javascript addEventListener而不选择子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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