javascript 为什么 e.stopPropagation() 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17681176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:10:59  来源:igfitidea点击:

Why does e.stopPropagation() not work?

javascriptevent-bubblingstoppropagation

提问by Ilyes512

I am reading a book called "Adaptive Web Design" by Aaron Gustafson were I got a piece of javascript that I didnt understand. While researching I find out about the difference between returning false and e.preventDefault. I also now know a little bit about the bubbeling effect of JavaScript and came to understand that to stop the bubbeling you can use e.stopPropagation() (in none-ie browser atleast).

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

I was playing around in fiddle but I couldnt get it working. I think it might got to do with the way the bubbeling takes effect (from root to the element and back?).

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

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.");
    }
}

Here is the fiddle: http://jsfiddle.net/MekZii/pmekd/(FIXED link) EDIT: I copy-pasted the wrong link! Its fixed now!

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

So what I would like to see is that when you click on the anchor, the onclick that is used on the div doesn't get executed (this is not a practical case, just a study case!)

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

采纳答案by Ilyes512

Ok, I found out that my first fiddle is wrong. I found another example that does work and shows how the stopPropagation() work:

好的,我发现我的第一个小提琴是错误的。我找到了另一个有效的例子,并展示了 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://jsfiddle.net/MekZii/wNGSx/2/

The example is found at the following link with some reading material: http://javascript.info/tutorial/bubbling-and-capturing

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

回答by Quentin

Events bubble from the element clicked on up to the document object.

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

Any event handler on a div is going to fire before an event handler on the body (since the body is an ancestor of it in the DOM).

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

By the time the event reaches the body, it is too late to prevent it from acting on a div.

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

回答by Tahir Alvi

Use below code wherever you want to cancel the event bubbling from child to parent in HTML

在您想取消 HTML 中从子级到父级的事件冒泡的任何位置使用以下代码

event.cancelBubble = true;

By using this way you stop the bubbling of event further upward from child to parent elements.

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