jQuery event.isDefaultPrevented()方法
jQuery isDefaultPrevented() 方法是一个内置的方法,它检查是否为事件调用了preventDefault()方法。这个方法返回一个布尔值。如果preventDefault()被调用,它返回True,否则返回False。
语法:
event.isDefaultPrevented()
参数:它接受一个参数event,它来自事件绑定函数。
例子1:这个例子检查isPreventDefault()方法是否在事件上调用。
<!doctype html>
<html>
<head>
<title>
isPreventDefault() Method
</title>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
</head>
<body>
<a href="https://www.geeksforgeeks.org">
Go to Homepage
</a>
<div id="initial"></div>
<div id="prevented"></div>
<div id="response"></div>
<!-- Script to check preventDefault() Method called or not -->
<script>
( "a" ).click(function( event ) {
( "#initial" ).html( "Before: isDefaultPrevented? <strong>"
+event.isDefaultPrevented()+"</strong>");
event.preventDefault();
( "#prevented" ).html( "preventDefault() is called now.");
( "#response" ).html( "So, you are not going anywhere."
+ " isDefaultPrevented? <strong>"
+ event.isDefaultPrevented() + "</strong>");
});
</script>
</body>
</html>
输出:
注意:粗体字(真/假)是isDefaultPrevented()方法的值。
示例2:本示例检查isDefaultPrevented()方法是否阻止默认动作。
<!doctype html>
<html>
<head>
<title>
isPreventDefault() Method
</title>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
</head>
<body>
<form action = "action.php">
Input:<br>
<input type="text" name="input_1">
<button type="submit">Submit</button>
</form>
<!-- Script to describe isDefaultPrevented() Method -->
<script>
$( "button" ).click(function( event ) {
if(event.isDefaultPrevented())
alert('Default action was prevented');
else
alert('Click Ok');
event.preventDefault();
if(event.isDefaultPrevented())
alert('Default action was prevented');
else
alert('Click Ok');
});
</script>
</body>
</html>
输出: