JavaScript 如何使用内联onclick属性停止事件传播
使用HTML DOM stopPropagation()方法来停止事件通过内联onclick属性进行传播,方法如下:
HTML DOM stopPropagation()事件方法:
stopPropagation()方法用于停止事件调用的传播,即父事件被调用时,我们可以使用stopPropagation()方法来阻止其子事件的调用,反之亦然。
语法:
event.stopPropagation()
示例1: 此示例通过在onclick事件中添加 stopPropagation方法 来停止事件传播<span>
元素。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to stop event propagation with
inline onclick attribute
</title>
<style>
div {
background: green;
}
span {
background: red;
color: white;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div onclick= "alert('you clicked the div')">
<span onclick= "event.stopPropagation();
alert('you clicked Span element(inside the div)');">
Span Content
</span>
</div>
</body>
</html>
输出:
- 在点击元素之前:
- 在点击 元素之后:
示例2: 此示例通过在元素的onclick事件中添加 stopPropagation()方法 来阻止事件传播。该示例通过将 window.event.cancelBubble 设置为true来处理 Internet Explorer 的情况。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to stop event propagation with
inline onclick attribute
</title>
<style>
div {
background: green;
}
span {
background: red;
color: white;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div onclick= "alert('you clicked the div')">
<span onclick= "StopEventPropagation(event);
alert('you clicked Span element(inside the div)');">
Span Content
</span>
</div>
<br>
<script>
function StopEventPropagation(event) {
if (event.stopPropagation) {
event.stopPropagation();
}
else if(window.event) {
window.event.cancelBubble=true;
}
}
</script>
</body>
</html>
输出:
- 在点击元素之前:
- 在点击
<span>
元素之后: