如何阻止事件冒泡

在页面开发中,我们使用JS添加事件后,默认情况事件会向上冒泡的。

<body>
	<div class="parent">
		<input type="button" class="child" value="仙剑奇侠传" >
	</div>
	<script src="https://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
	<script type="text/javascript">
		$(".child").click(function(){
			console.log('李逍遥');
		});
		$(".parent").click(function(){
			console.log('赵灵儿');
		});
	</script>
</body>

要阻止事件冒泡很简单,两个方法:1、调用event.stopPropagation()方法就行了,其中event就是事件参数;2、return false

event.stopPropagation()

<body>
	<div class="parent">
	    <input type="button" class="child" value="仙剑奇侠传" >
	</div>
	<script src="https://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
	<script type="text/javascript">
        //阻止事件冒泡,但不会阻止默认行为
		$(".child").click(function(event){
			console.log('李逍遥');
			event.stopPropagation();
		});
		$(".parent").click(function(){
			console.log('赵灵儿');
		});
	</script>
</body>

这样我们这里点击按钮后,就不会触发div的事件了,就是说事件没有冒泡到div层了。

return false

<body>
	<div class="parent">
	    <a href="https://www.baidu.com" class="child">仙剑奇侠传</a>
	</div>
	<script src="https://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
	<script type="text/javascript">
        //阻止事件冒泡,也阻止默认行为
		$(".child").click(function(event){
			console.log('李逍遥');
			return false;
		});
		$(".parent").click(function(){
			console.log('赵灵儿');
		});
	</script>
</body>

event.preventDefault()

<body>
	<div class="parent">
		<a href="https://www.baidu.com" class="child">仙剑奇侠传</a>
	</div>
	<script src="https://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
	<script type="text/javascript">
	    //不阻止事件冒泡,但阻止默认行为
		$(".child").click(function(event){
			console.log('李逍遥');
			event.preventDefault();
		});
		$(".parent").click(function(){
			console.log('赵灵儿');
		});
	</script>
</body>

总结: 

1.event.stopPropagation(); 
事件处理过程中,阻止了事件冒泡,但不会阻击默认行为(执行超链接的跳转) 
2.return false; 
事件处理过程中,阻止了事件冒泡,也阻止了默认行为(不执行超链接的跳转) 
还有一种与冒泡有关的: 
3.event.preventDefault(); 
事件处理过程中,不阻击事件冒泡,但阻击默认行为(它只执行所有弹框,却没有执行超链接跳转)

猜你喜欢

转载自blog.csdn.net/weixin_43804496/article/details/113248288
今日推荐