1.index() 方法返回指定元素的索引位置。
如果未找到元素,index() 将返回 -1
$(this).index()获取当前操作元素的索引值
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> span{ display: block;width: 200px;line-height: 30px;text-align: center; margin-top:20px ;background: #ccc; } button{ width: 200px;height: 50px;margin-top:50px ; } </style> <script src="../js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ //1.index() 方法返回指定元素的索引位置。 //如果未找到元素,index() 将返回 -1 // $(this).index()获取当前操作元素的索引值 $("#box span").click(function(){ var index = $(this).index(); alert(index); }); }) </script> </head> <body> <div id="box"> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> </div> <button>按钮</button> </body> </html>
复制
2. each( ) 方法规定为每个匹配元素规定运行的函数。就是对元素遍历(做循环)
each()函数可以接收正在遍历元素的索引
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> span{ display: block;width: 200px;line-height: 30px;text-align: center; margin-top:20px ;background: #ccc; } button{ width: 200px;height: 50px;margin-top:50px ; } </style> <script src="../js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ //2.each() 方法规定为每个匹配元素规定运行的函数。就是对元素遍历(做循环) //each()函数可以接收正在遍历元素的索引如遍历一个传一个索引 $("button").click(function(){ $("#box span").each(function(i){//each给获取的span元素集合做遍历 //$(this).text("我要自学网"); $(this).text("我要自学网"+i); $(this).attr("id","zxw"+i);//通过遍历给元素添加属性,及属性值 }); }); }) </script> </head> <body> <div id="box"> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> <span>51zxw</span> </div> <button>按钮</button> </body> </html>
复制