JavaScript preventDefault()和stopPropagation()方法的区别
在本文中,我们将讨论preventDefault()和stopPropagation()方法,并为每个条件提供适当的代码示例,然后我们将看到preventDefault()与stopPropagation()之间的区别。
JavaScript preventDefault()方法: : 这是事件接口中存在的一个方法。该方法阻止浏览器执行所选元素的默认行为。只有可取消的事件才能取消该事件。例如,有些事件是无法阻止的,例如滚动和滚轮事件。
语法:
event.preventDefault();
参数: 该方法不接受任何参数。
我们将通过示例来看如何应用这两种方法。
示例1: 阻止链接跟随URL,使浏览器无法跳转到另一个页面。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Using jquery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<a id="first" href="www.geeksforgeeks.com">
GeeksForGeeks
</a>
<script>
$("#first").click(function () {
event.preventDefault();
alert("Event prevented, Can't go there.");
});
</script>
</body>
</html>
输出:
示例 2: 它阻止用户勾选复选框。通常情况下,当我们点击复选框时,它会切换状态,但是在调用preventDefault()方法后,什么都不会发生。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Using jquery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<input type="checkbox" id="f" />
click on this box
<script>
$("#f").click(function () {
event.preventDefault();
alert("Event prevented");
});
</script>
</body>
</html>
输出:
JavaScript stopPropagation() 事件方法 : 此方法用于阻止父元素访问事件。基本上,这个方法用于阻止相同事件的传播被调用。例如,我们在一个 div 标签中有一个 button 元素,它们都有一个 onclick 事件。当我们尝试触发与 button 元素相关联的事件时,与 div 元素相关联的事件也会被执行,因为 div 是 button 元素的父元素。
语法:
event.stopPropagation();
我们可以通过使用 stopPropagation() 方法来解决这个问题,因为这样可以阻止父元素访问事件。
示例 1:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<div class="first" onclick="functionFirst()">
<button onclick="functionSecond()">
Button
</button>
</div>
<script>
function functionSecond() {
alert("button hello");
}
function functionFirst() {
alert("div hello");
}
</script>
</body>
</html>
输出:
在这里,点击按钮之后, 两个函数都将执行。
示例 2:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<div class="first" onclick="functionFirst()">
<button onclick="functionSecond()">
Button
</button>
</div>
<script>
function functionSecond() {
event.stopPropagation();
alert("button hello");
}
function functionFirst() {
alert("div hello");
}
</script>
</body>
</html>
输出:
现在,在这种情况下,我们添加了一个 event.stopPropagation() 方法,那么只有 button 元素的功能会被执行。
preventDefault()和stopPropagation()方法之间的区别:
event.preventDefault()方法 | event.stopPropagation()方法 |
---|---|
阻止浏览器采取默认行为。 | 阻止父元素或子元素进一步传播当前事件。 |
这是事件接口中的一个方法。 | 这个方法也存在于事件接口中。 |
例如,它阻止浏览器跟随链接。 | 它无法停止浏览器的默认行为。 |
它的语法是-: event.preventDefault(); | 它的语法是-: event.stopPropagation(); |
这个方法不接受任何参数。 | 这个方法的定义中也没有参数。 |
它支持的浏览器有-:chrome, firefox, safari, opera, 等等 | 它支持的浏览器有-:chrome, firefox, safari, opera, 等等 |
它不返回值。 | 它没有返回类型。 |
它使用DOM Level 3 事件的DOM版本。 | 它使用DOM Level 2 事件的DOM版本。 |