如何使用jQuery删除一个事件处理程序
这里,任务是在jQuery/JavaScript中删除一个事件处理程序。有三种方法可以解决这个问题,下面将讨论。
使用unbind()方法:它是jQuery中的一个内置方法,用于删除任何选定的事件处理程序。
语法:
$(selector).unbind(event, function, eventObj)
方法:
- 选择要删除事件处理程序的选择器。
- 使用unbind()方法来删除事件。
- 在点击解除绑定工作的函数后,将删除事件处理程序。
示例 1:
<!DOCTYPE html>
<html>
<head>
<title>
jQuery | How to remove an event handler?
</title>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<h3>
Remove an event handler using unbind method
</h3>
<h4>Element to remove</h4>
<button>
Click Here
<script>
(document).ready(function() {
("h4").click(function() {
(this).slideToggle();
});
("button").click(function() {
$("h4").unbind();
});
});
</script>
</body>
</html>
输出:
- 在点击任何地方之前。
- 点击元素h4后。
- 点击按钮后,事件将不工作。
使用off()方法:它用于移除与on()方法相连的事件处理程序。
语法:
$(selector).off(event, selector, function(eventObj), map)
方法:
- 选择要删除事件处理程序的选择器。
- 使用off()方法来删除事件。
- 在点击解除绑定工作的函数后,将删除事件处理程序。
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>
jQuery | How to remove an event handler?
</title>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<h3>
Remove an event handler using off method
</h3>
<h4>Element to remove</h4>
<button>
Click Here
<script>
(document).ready(function() {
("h4").click(function() {
(this).slideToggle();
});
("button").click(function() {
$("h4").off();
});
});
</script>
</body>
</html>
输出:
- 在点击任何地方之前。
- 点击元素h4后。
- 点击按钮后,事件将不工作。