如何使用jQuery删除一个事件处理程序

如何使用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> 

输出:

  • 在点击任何地方之前。

如何使用jQuery删除一个事件处理程序?

  • 点击元素h4后。

如何使用jQuery删除一个事件处理程序?

  • 点击按钮后,事件将不工作。

如何使用jQuery删除一个事件处理程序?

使用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> 

输出:

  • 在点击任何地方之前。

如何使用jQuery删除一个事件处理程序?

  • 点击元素h4后。

如何使用jQuery删除一个事件处理程序?

  • 点击按钮后,事件将不工作。

如何使用jQuery删除一个事件处理程序?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程