遍历元素

在jQuery中,可以直接使用each()方法实现元素的遍历。


语法格式: each(callback)


其中,参数callback是一个function函数,该函数还可以接受一个形参Index,此形参为遍历元素的序号(从0开始);如果需要访问元素中的属性,可以借助形参Index,配合this关键字来实现元素属性的设置或获取。

例:


(1)功能描述:在页面中,设置几个色块,通过each()方法遍历全部色块,并设置每个色块的title属性。


(2)实现代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 5 <title>jQuery遍历元素</title>
 6 <style>
 7     *{margin: 0;padding: 0}
 8     body{padding: 100px;}
 9     ul{border: solid 1px #f13;overflow: hidden;}
10     li{list-style: none;width: 50px;height: 50px;float: left;margin: 3px;background: orange;}
11 </style>
12 <script type="text/javascript" src="jquery-1.8.3.js"></script>
13 <script>
14     $(function(){
15         $("li").each(function(index){
16             //根据形参index设置元素的title属性,index从0开始
17             this.title = "" + index + "个色块。";
18         });
19     });
20 </script>
21 </head>
22 <body>
23     <ul>
24         <li></li>
25         <li></li>
26         <li></li>
27         <li></li>
28         <li></li>
29     </ul>
30 </body>
31 </html>
View Code

(3)结果如下图所示:

高否?富否?帅否? 否? 滚去学习!
原文地址:https://www.cnblogs.com/baixc/p/3387743.html