事件传播和多个事件处理程序
好吧,我很困惑。我在 document
上有一个全局点击事件处理程序。在页面上我有一些链接。每个链接都由相同的单击事件处理程序处理,该处理程序除其他外,还可以防止事件冒泡到文档级别并防止链接执行。在这些链接中,有一个特定的点击处理程序,应该执行其任务,然后将事件传递给链接的通用点击事件。但事实并非如此。
document.onclick = function()
{
document.body.innerHTML += "You clicked me!";
};
document.getElementsByTagName("a")[0].onclick = function(e) {
this.innerHTML += " Click it!";
e.stopPropagation();
//This return false appears only to
//prevent the link from its default action
return false;
};
document.getElementById("link").onclick = function(e) {
this.innerHTML += " Go ahead, ";
//But this return false appears to stop
//the propagation up to the previous event
//I would think that removing the link below
//would cause the event to propagate to the event
//above which would then stop the propagation and
//prevent the default, but apparently this is
//not the case; removing the line below causes
//the link to load Google like normal
return false;
};
如何让较低的事件触发并触发较高的事件,然后取消该事件?
明白我的意思此处
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
哈,呃。使用
element.on
只是在 DOM 中为元素设置属性,这意味着每个事件只能有一个处理程序。相反,我需要使用addEventListener
并结合正确使用event.preventDefault()
和event.stopPropagation()
在我的第一次尝试中,我把我想成为第一个处理程序的东西放在第二位,但这实际上意味着它会覆盖第一个处理程序。在这种情况下,我需要先放置我想要的处理程序,因为该处理程序附加到该事件。
我修改后的代码应该是:
http://jsbin.com/ecozep/8/edit
Ha, duh. using
element.on<event>
is simply setting the property in the DOM for the element, which means each event can only have one handler. Instead, I need to useaddEventListener
combined with a proper use ofevent.preventDefault()
andevent.stopPropagation()
In my first attempts, I was putting what I wanted to be the first handler second, but that really meant it was overriding the first. In this case, I need to put the handler I want first first, since the handler is being attached to the event.
My revised code should be:
http://jsbin.com/ecozep/8/edit