jQuery delegate()方法

jQuery delegate()方法

jQuery中的委托()方法是用来添加一个或多个事件处理程序到指定的元素,这些元素是选定的元素的孩子,也是用来指定一个函数,每当事件发生时运行。

语法

$(selector).delegate( childSelector, event, data, function )

参数:该方法接受上面提到的和下面描述的四个参数。

  • childSelector。这是必须的参数,用于指定一个或多个附属于事件处理程序的子元素。
  • event。这是一个必要的参数,用于指定一个或多个附加到元素的事件。多个事件值用空格隔开,而且必须是一个有效的事件。
  • data。它是一个可选的参数,用于指定沿着函数传递的额外数据。
  • function。这是必要参数,用于指定事件发生时要运行的函数。

示例 1:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>
            delegate() Method in jQuery
        </title> 
          
        <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
          
        <!-- jQuery script to add events -->
        <script>
            (document).ready(function() {
                ("div").delegate("h3", "click", function() {
                    $("h3").css("background-color", "green");
                });
            });
        </script>
    </head>
      
    <body> 
        <center>
            <h1>Welcome to GeeksforGeeks!</h1> 
              
            <p>
                Click on the below element (lightgreen
                background) to change background-color
            </p>
              
            <div style="background-color:lightgreen;">
                <h3>GeeksForGeeks</h3>
            </div>
   
            <h3>GeeksForGeeks.</h3>
      </center>
    </body> 
</html>   

输出:
在点击元素之前:
jQuery delegate()方法
点击元素后:
jQuery delegate()方法

示例 2:

<!DOCTYPE html> 
<html> 
    <head> 
        <title>
            delegate() Method in jQuery
        </title> 
          
        <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
          
        <!-- jQuery script for delegate() method -->
        <script>
            (document).ready(function(){
                ("div").delegate("h3", "click", function(){
                    (this).slideToggle();
                });
                  
                ("button").click(function(){
                    $("<h3>This show how the delegate Method" 
                    + " works .</h3>").insertAfter("button");
                });
            });
        </script>
    </head> 
      
    <body> 
        <center>
            <h1>Welcome to GeeksforGeeks!.</h1> 
            
          <div style="background-color:green">
                
              <h3>GeeksforGeeks.</h3>
              <h3>The delegate Method.</h3>
                
              <button>Click</button>
          </div>
      </center>
    </body> 
</html>   

输出:
在点击按钮之前:
jQuery delegate()方法
点击按钮后:
jQuery delegate()方法

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程