each()遍历

在《jQuery教程/理解选取更新范围》一节中,我们知道:当选择器返回了多个元素时,可以使用一个方法来更新所有的元素,不再需要使用循环。

然后有的时候需要遍历元素,怎么办?

使用each()方法可以遍历。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
< html >
     < head >
         < meta charset = "UTF-8" >
         < title >each()遍历</ title >
         < script src = "https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js" ></ script >
     </ head >
     < body >     
         < div >
             < ul id = "ul" >
                 < li id = "a" >键盘</ li >
                 < li id = "b" >鼠标</ li >
                 < li id = "c" >屏幕</ li >
                 < li id = "d" >< a >电源</ a ></ li >
             </ ul >
         </ div >
         < script >
             $('li').each(function(){
                 // 获取每个li元素的id
                 var ids=this.id;
                  // li元素的id追加到li元素后面
                 $(this).append('< em >'+ids+'</ em >');
             });
         </ script >
     </ body >
</ html >

猜你喜欢

转载自www.cnblogs.com/max-hou/p/9132457.html