开发者

How to Stop Bubbling on DOMSubtreeModified Event?

开发者 https://www.devze.com 2023-03-21 23:10 出处:网络
I have a pretty simple scenario. I have the following HTML: <h1>Hello</h1> <input type="button" value="Change" id="change" />

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消