jQuery如何使用delegate()方法?代码示例

2021年3月30日10:30:35 发表评论 599 次浏览

delegate()方法jQuery中的jQuery用于向指定元素添加一个或多个事件处理程序, 这些事件处理程序是选定元素的子级, 并且还用于指定一个函数, 以在事件发生时立即运行。

语法

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

参数:此方法接受上述和以下所述的四个参数:

  • childSelector:它是必填参数, 用于指定附加到事件处理程序的一个或多个子元素。
  • 事件:它是必填参数, 用于指定附加到元素的一个或多个事件。多个事件值由空格分隔, 并且必须是有效事件。
  • 数据:它是一个可选参数, 用于指定要传递给该函数的其他数据。
  • 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 lsbin!</ h1 > 
              
             < p >
                 Click on the below element (lightgreen
                 background) to change background-color
             </ p >
              
             < div style = "background-color:lightgreen;" >
                 < h3 >lsbin</ h3 >
             </ div >
   
             < h3 >lsbin.</ h3 >
       </ center >
     </ body > 
</ html >

输出如下:

在单击元素之前:

jQuery如何使用delegate()方法?代码示例1

单击元素后:

jQuery如何使用delegate()方法?代码示例2

范例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 lsbin!.</ h1 > 
            
           < div style = "background-color:green" >
                
               < h3 >lsbin.</ h3 >
               < h3 >The delegate Method.</ h3 >
                
               < button >Click</ button >
           </ div >
       </ center >
     </ body > 
</ html >

输出如下:

之前单击按钮:

jQuery如何使用delegate()方法?代码示例3

单击按钮后:

jQuery如何使用delegate()方法?代码示例4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: