jQuery中event.stopPropagation()阻止事件冒泡及event.preventDefault()阻止默认行为

如下代码, div里面包裹了p,p里面包裹了span

当我们点击span时,其实同时也点击了p和div,这时三个click事件中的alert方法都会执行

这时在span的click方法中添加event.stopPropagation(),则会阻止点击事件向上冒泡,只会alert()span的而其他两个方法不会执行


<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").click(function(event){
    event.stopPropagation(); //阻止时间冒泡
    alert("The span element was clicked.");
  });
  $("p").click(function(event){
    alert("The p element was clicked.");
  });
  $("div").click(function(){
    alert("The div element was clicked.");
  });
});
</script>
</head>
<body>

<div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
	This is a div element.
	<p style="background-color:pink">This is a p element, in the div element. <br>
		<span style="background-color:orange">
			This is a span element in the p and the div element.
		</span>
	</p>
</div>

<p>
	<b>Note:</b> Click on each of the elements above. When clicking on the 
	<b>div</b> 
element, it will alert that the div element was clicked. When clicking on the 
	<b>p</b> 
element, it will return both the p and the div element, since the p element is inside the div element. 
But when clicking on the 
	<b>span</b> 
element, it will only return itself, and not the p and the div element (even though its inside these elements).  The event.stopPropagation() stops the click event from bubbling to the parent elements. 
</p>


<p>
	<b>Tip:</b>
	 Try to remove the event.stopPropagation() line, and click on the span element again (the click event will now bubble up to parent elements).
</p>

</body>
</html>


event.preventDefault()阻止事件默认行为:

比如在网页右键鼠标,会弹出浏览器自带的菜单

而我们给右键事件添加此代码后,会阻止自带菜单的弹出,而执行我们自己下面写的代码




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值