Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - event.stopPropagation和event.preventDefault有什么区别?(What's the difference between event.stopPropagation and event.preventDefault?)

They seem to be doing the same thing... Is one modern and one old?

(他们似乎在做同样的事情……是现代的还是老的?)

Or are they supported by different browsers?

(还是不同的浏览器支持它们?)

When I handle events myself (without framework) I just always check for both and execute both if present.

(当我自己处理事件(没有框架)时,我总是检查两者并执行(如果存在)。)

(I also return false , but I have the feeling that doesn't work with events attached with node.addEventListener ).

((我也return false ,但是我感觉不适用于与node.addEventListener事件)。)

So why both?

(那么为什么两者都呢?)

Should I keep checking for both?

(我应该继续检查两者吗?)

Or is there actually a difference?

(还是实际上有区别?)

(I know, a lot of questions, but they're all sort of the same =))

((我知道,很多问题,但都是相同的=))

  ask by Rudie translate from so

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

1 Answer

0 votes
by (71.8m points)

stopPropagation stops the event from bubbling up the event chain.

(stopPropagation阻止事件冒泡事件链。)

preventDefault prevents the default action the browser makes on that event.

(preventDefault防止浏览器对该事件执行默认操作。)

Examples (例子)

preventDefault

(preventDefault)

 $("#but").click(function (event) { event.preventDefault() }) $("#foo").click(function () { alert("parent click event fired!") }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="foo"> <button id="but">button</button> </div> 

stopPropagation

(停止传播)

 $("#but").click(function (event) { event.stopPropagation() }) $("#foo").click(function () { alert("parent click event fired!") }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="foo"> <button id="but">button</button> </div> 

With stopPropagation , only the button 's click handler is called while the div 's click handler never fires.

(使用stopPropagation ,仅调用button的单击处理程序 ,而div的单击处理程序从不触发。)

Where as if you use preventDefault , only the browser's default action is stopped but the div's click handler still fires.

(就好像您使用了preventDefault ,只有浏览器的默认操作停止了,而div的单击处理程序仍然会触发。)

Below are some docs on the DOM event properties and methods from MDN:

(以下是有关MDN的DOM事件属性和方法的一些文档:)

For IE9 and FF you can just use preventDefault & stopPropagation.

(对于IE9和FF,您可以仅使用preventDefault和stopPropagation。)

To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

(为了支持IE8和更低版本,将stopPropagation替换为cancelBubble ,将preventDefault替换为returnValue)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...