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
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…