简体   繁体   中英

How to Stop Bubbling on DOMSubtreeModified Event?

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.net/sECtq/ . Any help would be appreciated. Thanks.

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 eg 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.com/event.isPropagationStopped l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM