【问题标题】:Why does e.stopPropagation() not work?为什么 e.stopPropagation() 不起作用?
【发布时间】:2013-07-16 15:47:27
【问题描述】:

我正在阅读 Aaron Gustafson 的一本名为“自适应网页设计”的书,如果我有一段我不理解的 javascript。在研究时,我发现了返回 false 和 e.preventDefault 之间的区别。我现在也对 JavaScript 的冒泡效果有了一些了解,并且开始明白要停止冒泡,您可以使用 e.stopPropagation() (至少在无浏览器中)。

我在玩小提琴,但我无法让它工作。我认为这可能与冒泡生效的方式有关(从根到元素再返回?)。

document.body.onclick = function (e) {
    alert("Fired a onclick event!");
    e.preventDefault();
    if ('bubbles' in e) { // all browsers except IE before version 9
        if (e.bubbles) {
            e.stopPropagation();
            alert("The propagation of the event is stopped.");
        } else {
            alert("The event cannot propagate up the DOM hierarchy.");
        }
    } else { // Internet Explorer before version 9
        // always cancel bubbling
        e.cancelBubble = true;
        alert("The propagation of the event is stopped.");
    }
}

这里是小提琴:http://jsfiddle.net/MekZii/pmekd/(固定链接) 编辑: 我复制粘贴了错误的链接!现在修好了!

所以我想看到的是,当你点击锚点时,在 div 上使用的 onclick 不会被执行(这不是一个实际案例,只是一个研究案例!)

【问题讨论】:

  • 您链接到的代码与问题中的代码不同。它们都不包含 div。

标签: javascript event-bubbling stoppropagation


【解决方案1】:

事件从被点击的元素冒泡到文档对象。

div 上的任何事件处理程序都会在 body 上的事件处理程序之前触发(因为 body 是它在 DOM 中的祖先)。

当事件到达 body 时,阻止它作用于 div 为时已晚。

【讨论】:

  • 这是否意味着不触发 div 的 onclick 就无法点击链接?如果那是真的,那么我不明白为什么以及何时使用 stopPropagation() 函数。
  • 带有附加到链接的事件处理程序 - 当然。不过,您有一个附加到正文的事件处理程序。
【解决方案2】:

好的,我发现我的第一个小提琴是错误的。我发现了另一个确实有效的示例,并展示了 stopPropagation() 的工作原理:

var divs = document.getElementsByTagName('div');

for(var i=0; i<divs.length; i++) {
  divs[i].onclick = function( e ) {
    e = e || window.event;
    var target = e.target || e.srcElement;

    //e.stopPropagation ? e.stopPropagation() : ( e.cancelBubble = true );
    if ('bubbles' in e) { // all browsers except IE before version 9
        if (e.bubbles) {
            e.stopPropagation();
            alert("The propagation of the event is stopped.");
        } else {
            alert("The event cannot propagate up the DOM hierarchy.");
        }
    } else { // Internet Explorer before version 9
        // always cancel bubbling
        e.cancelBubble = true;
        alert("The propagation of the event is stopped.");
    }

    this.style.backgroundColor = 'yellow';

    alert("target = " + target.className + ", this=" + this.className );

    this.style.backgroundColor = '';
  }
}

http://jsfiddle.net/MekZii/wNGSx/2/

该示例可在以下链接中找到,其中包含一些阅读材料: http://javascript.info/tutorial/bubbling-and-capturing

【讨论】:

    【解决方案3】:

    在您想取消 HTML 中从子级到父级的事件冒泡时使用下面的代码

    event.cancelBubble = true;
    

    通过使用这种方式,您可以阻止事件从子元素到父元素进一步向上冒泡。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 2019-08-06
      • 2016-07-05
      • 2011-08-06
      • 2013-01-18
      相关资源
      最近更新 更多