Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

events - Javascript : How to enable stopPropagation?

With object.stopPropagation() I can stop event bubbling but how can I re-enable it?

Is there a pre defined function in js something like object.startPropagation?

EDIT:

The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't remember the value at all. The event e is new each time onclick is fired. The problem is you're always cancelling the event bubbling:

if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}
  • e.stopPropagation is the W3C method of preventing event bubbling.
  • e.cancelBubble is the Microsoft method to prevent event bubbling.

They're both the same. So you're cancelling bubbling of events every time. More reading here.

You'll need to change your method so that it only cancels bubbling if your criteria are met:

document.getElementById("object").onclick = function(e) {

    if(e && e.stopPropagation && someCriteriaToStopBubbling === true) 
    {
        e.stopPropagation();
    } 
    else if (someCriteriaToStopBubbling === true)
    {
          e = window.event;
          e.cancelBubble = true;
    }
}

UPDATE: Bear in mind that in your current code, if (e && e.stopPropagation) will always be true if the browser supports stopPropagation. If it goes into the second brace for cancelBubble, it will not remember the value last set. See this fiddle.

Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...