最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Stop Bubbling on DOMSubtreeModified Event? - Stack Overflow

programmeradmin4浏览0评论

I have a pretty simple scenario. I have the following HTML:

<h1>Hello</h1>
<input type="button" value="Change" id="change" />

With the corresponding JS:

var h1 = $("h1").get(0);

h1.addEventListener("DOMSubtreeModified", function(ev) {

    console.log("Changed");
    
    ev.bubbles = false;
    ev.cancelBubble = true;
    ev.defaultPrevented = true;
    ev.preventDefault();
    ev.stopPropagation();
    ev.returnValue = false;
    
    return false;
    
}, false);

$("#change").click(function() {
    $("h1").text("World");
});

So, this basically just changes the text of the H1 node and the event is then fired. However, the event is firing twice (as I assume as a result of bubbling). As you can see, I've tried throwing everything at it to try to get it to not fire twice, but that does not stop it. If you want to play with the code, you can check it out at: /. Any help would be appreciated.

I have a pretty simple scenario. I have the following HTML:

<h1>Hello</h1>
<input type="button" value="Change" id="change" />

With the corresponding JS:

var h1 = $("h1").get(0);

h1.addEventListener("DOMSubtreeModified", function(ev) {

    console.log("Changed");
    
    ev.bubbles = false;
    ev.cancelBubble = true;
    ev.defaultPrevented = true;
    ev.preventDefault();
    ev.stopPropagation();
    ev.returnValue = false;
    
    return false;
    
}, false);

$("#change").click(function() {
    $("h1").text("World");
});

So, this basically just changes the text of the H1 node and the event is then fired. However, the event is firing twice (as I assume as a result of bubbling). As you can see, I've tried throwing everything at it to try to get it to not fire twice, but that does not stop it. If you want to play with the code, you can check it out at: http://jsfiddle/sECtq/. Any help would be appreciated.

Share Improve this question edited Jan 13, 2023 at 13:58 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 22, 2011 at 1:41 naivedevelopernaivedeveloper 2,9588 gold badges37 silver badges49 bronze badges 1
  • ev.preventDefault(); will cause IE to throw an exception – qwertymk Commented Jul 22, 2011 at 2:24
Add a ment  | 

2 Answers 2

Reset to default 7

This behaviour is not caused by bubbling.

$.text() executes 2 steps to set the new text:

  1. remove the existing contents
  2. insert a new textNode

Both steps trigger DOMSubtreeModified, so you get 2 alerts.

You may use e.g. the following:

$("h1")[0].firstChild.data="World";

This will only change the contents of the textNode without removing a node.

or you can also check whether propagation has been stopped or not. Take a look on the http://api.jquery./event.isPropagationStopped l

发布评论

评论列表(0)

  1. 暂无评论