jQuery event.stopPropagation()方法
jQuery的event.stopPropagation()方法是一个内置的方法,用于停止窗口的传播。在DOM树中,当设置一个事件的子元素和父元素时,如果你点击了子元素的事件,它将同时调用子元素和父元素。所以在这个方法的帮助下,除了选定的元素外,其他元素不会出现弹出窗口。
语法:
event.stopPropagation()
参数:它接受单个参数,这是强制性的。这个参数来自绑定函数。
例子1:这个例子说明了event.stopPropagation()方法。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery event.stopPropagation() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
.main {
border: 1px solid green;
padding: 20px;
width: 60%;
}
</style>
<!-- Script to use jQuery event.stopPropagation() Method -->
<script>
(document).ready(function () {
(".main").click(function () {
alert("Main div element");
});
(".GFG").click(function (event) {
event.stopPropagation();
alert("Nested div element");
});
(".geeks").click(function (event) {
alert("Second nested div element");
});
});
</script>
</head>
<body>
<!-- Click on element to display alert message -->
<div class="main">
GeeksforGeeks
<div class="GFG">
A computer science portal
<div class="geeks">
Welcome to GeeksforGeeks
</div>
</div>
</div>
</body>
</html>
输出:
例子2:在这个例子中,当我们点击文本时,颜色将发生变化。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery event.stopPropagation() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
.main {
border: 1px solid green;
padding: 20px;
width: 60%;
}
</style>
<!-- Script to use jQuery event.stopPropagation() Method -->
<script>
(document).ready(function () {
(".GFG").click(function (event) {
event.stopPropagation();
(".GFG").css( "color", "red");
});
(".geeks").click(function (event) {
$(".geeks").css( "color", "green");
});
});
</script>
</head>
<body>
<!-- Click on element to change the color -->
<div class="GFG">
GeeksforGeeks
<div class="geeks">
A computer science portal
</div>
</div>
</body>
</html>
输出: