且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

event.stopPropagation和event.preventDefault之间有什么区别?

更新时间:2023-12-04 12:01:10

stopPropagation 阻止事件冒泡起事件链。



preventDefault 阻止浏览器对该事件执行的默认操作。



让我们说你有

 < div id =foo> 
< button id =but/>
< / div>

$(#foo)。click(function(){
//鼠标点击div
});

$(#but)。click(function(ev){
//鼠标点击按钮
ev.stopPropagation();
});

示例



 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script&gt ;< div id =foo> < button id =but> button< / button>< / div>  



  $(#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&gt ;< / script>< div id =foo> < button id =but> button< / button>< / div>  



使用 stopPropagation 只调用按钮点击处理程序,而 divs点击处理程序永远不会触发



如果您只是 preventDefault ,则只有浏览器的默认操作被停止,但是div的点击处理程序仍然触发。



以下是来自 MDN MSDN $的DOM事件对象的一些文档c $ c>



MSDN:





MDN:





对于IE9和FF,您只需使用preventDefault& stopPropagation。



为了支持IE8,并将 stopPropagation 替换为 cancelBubble 并用 returnValue


替换 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).

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 =))

stopPropagation stops the event from bubbling up the event chain.

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

Let's say you have

<div id="foo">
 <button id="but" />
</div>

$("#foo").click(function() {
   // mouse click on div
});

$("#but").click(function(ev) {
   // mouse click on button
   ev.stopPropagation();
});

Example

$("#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>

$("#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 buttons click handler is called and the divs click handler never fires.

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

Below are some docs on the DOM event objects from MDN and MSDN

MSDN:

MDN:

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

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