jQuery如何使用each()方法处理DOM元素?

2021年3月26日16:31:47 发表评论 806 次浏览

each()方法在jQuery中, 用于指定要为每个匹配的元素运行的函数。

语法如下:

$(selector).each(function(index, element))

参数:此方法接受单个参数函数(索引, 元素)这是强制性的。它用于为每个匹配的元素运行。它包含两个参数。

  • 指数:它保存选择器元素的索引位置。
  • 元件:它保存当前元素。

范例1:本示例使用each()方法显示每个段落元素。

<!DOCTYPE html>
< html >
  
< head > 
     < title >
         jQuery Misc each() Method
     </ title >
      
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
</ head > 
  
< body style = "text-align:center;" >
  
     < h1 style = "color:green;" >  
         lsbin
     </ h1 >  
      
     < h2 >jQuery each() Method</ h2 >
  
     < button >Click</ button >
      
     < p >Geeks1</ p >
     < p >Geeks2</ p >
     < p >Geeks3</ p >
      
     <!-- Script use each() method -->
     < script >
         $(document).ready(function() {
             $("button").click(function() {
                 $("p").each(function() {
                     alert($(this).text())
                 });
             });
         });
     </ script >
</ body >
  
</ html >

输出如下:

在点击按钮之前

jQuery如何使用each()方法处理DOM元素?1

单击按钮后

jQuery如何使用each()方法处理DOM元素?2
jQuery如何使用each()方法处理DOM元素?3
jQuery如何使用each()方法处理DOM元素?4

范例2:本示例使用each()方法显示段落元素。

<!DOCTYPE html>
< html >
  
< head > 
     < title >
         jQuery Misc each() Method
     </ title >
      
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
</ head > 
  
< body style = "text-align:center;" >
  
     < h1 style = "color:green;" >  
         lsbin
     </ h1 >  
      
     < h2 >jQuery each() Method</ h2 >
  
     < button >Click</ button >
      
     < p >Geeks1-Geeks2-Geeks3</ p >
      
     < div style = "color:lightgreen;" ></ div >
      
     <!-- Script use each() method -->
     < script >
         $(document).ready(function(){
             $("button").click(function(){
                 $("p").each(function(){
                     $("div").text($(this).text())
                 });
             });
         });
     </ script >
  </ body >
  
</ html >

输出如下:

在点击按钮之前

jQuery如何使用each()方法处理DOM元素?5

单击按钮后

jQuery如何使用each()方法处理DOM元素?6

木子山

发表评论

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