1

好吧,我很困惑。我有一个全局点击事件处理程序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;
};

如何让较低的事件触发并达到较高的事件,然后取消该事件?

看看我在这里的意思

4

1 回答 1

2

哈,呵呵。usingelement.on<event>只是在 DOM 中为元素设置属性,这意味着每个事件只能有一个处理程序。相反,我需要addEventListener结合正确使用event.preventDefault()andevent.stopPropagation()

在我的第一次尝试中,我将我想成为的第一个处理程序放在第二位,但这确实意味着它覆盖了第一个。在这种情况下,我需要首先放置我想要的处理程序,因为处理程序被附加到事件。

我修改后的代码应该是:

document.onclick = function()
  {
   document.body.innerHTML += "You clicked me!"; 
};
document.getElementById("link").addEventListener("click",function() {
  this.innerHTML += " Go ahead, ";
});
  document.getElementsByTagName("a")[0].addEventListener("click",function(e) {
   this.innerHTML += " Click it!"; 
    e.stopPropagation();
    e.preventDefault();
   });

http://jsbin.com/ecozep/8/edit

于 2011-07-20T19:57:10.637 回答