首页 > 其他 > 详细

e.preventDefault()与e.stopPropagation()的区别

时间:2019-05-13 17:43:56      阅读:113      评论:0      收藏:0      [点我收藏+]

e.stopPropagation()阻止事件冒泡
<table border=‘1‘>
<tr>
<td><span>冒泡事件测试</span></td>
<td><span>冒泡事件测试2</span></td>
</tr>
</table>
我们先看这段js代码:

<script>
$(‘table‘).on(‘click‘, function (e) {
alert(‘table alert!‘);
});
$(‘tr‘).on(‘click‘,function(){
alert(‘tr alert‘);
});
$(‘span‘).on(‘click‘,function(){
alert("span alert!")
});
</script>
我们会看到这样的情况:span alert -> td alert -> table alert。这就叫事件冒泡。就是从下到上,从里到外,事件依次触发。

 

有的时候我们不希望事件冒泡咋办?

<script>
$(function(){
$(‘table‘).on(‘click‘,‘span‘,function(e){
alert(‘span alert!‘);
e.stopPropagation();
});
$(‘table‘).on(‘click‘,function(){
alert(‘table alert!‘);
});
})
</script>
这样,点击span时,弹出"span alert!"对话框即结束,然后禁止事件冒泡,“table alert!”对话框即不会触发。

 

如果想获得事件相关信息,就要给匿名方法加一个e对象,e就是事件对象。

 

e.preventDefault()阻止事件默认行为。


$("a").click(function (e) {
     alert("默认行为被禁止喽");
     e.preventDefault();
});

<a href="http://www.baidu.com">测试</a>

 

return false等效于同时调用e.preventDefault()和e.stopPropagation()

 

return false除了阻止默认行为之外,还会阻止事件冒泡。如果手上有一份jquery源代码的话,可查看其中有如下代码:

if (ret===false){
  event.preventDefault();
  event.stopPropagation();
}
----------------------------------------------------------------------------------------- 

原文:https://blog.csdn.net/xiaobing_hope/article/details/50674998

e.preventDefault()与e.stopPropagation()的区别

原文:https://www.cnblogs.com/showcase/p/10857712.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!