js屏蔽父元素的事件响应
源码示例:
<!DOCTYPE html>
<html>
<head>
<title>Simple html page</title>
</head>
<body>
<div id="container" style="width:200px;border:1px solid blue;">
<input type="button" value="Click me" id="click-me"/>
</div>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//div注册click事件
$("#container").click(function(){
alert("This is container");
});
//按钮注册click事件
$("#click-me").click(function(e){
//屏蔽父元素的事件响应
e.stopPropagation();
alert("This is Click me button");
});
});
</script>
</body>
</html>
源码示例:
<!DOCTYPE html>
<html>
<head>
<title>Simple html page</title>
</head>
<body>
<div id="container" style="width:200px;border:1px solid blue;">
<input type="button" value="Click me" id="click-me"/>
</div>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//div注册click事件
$("#container").click(function(){
alert("This is container");
});
//按钮注册click事件
$("#click-me").click(function(e){
//屏蔽父元素的事件响应
e.stopPropagation();
alert("This is Click me button");
});
});
</script>
</body>
</html>
本文通过一个简单的HTML示例展示了如何使用JavaScript(这里使用了jQuery库)来阻止父元素的事件响应。通过调用`event.stopPropagation()`方法,可以确保点击按钮时,只会触发按钮自身的点击事件,而不会触发其父元素——`container`的点击事件。
117

被折叠的 条评论
为什么被折叠?



