jquery 之 $().each和$.each()
一、选择器+遍历(dom操作)分为两种:
第一种:
$('div').each(function (i){
i就是索引值
this 表示获取遍历每一个dom对象
});
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style type="text/css"> *{ margin:0; padding:0; } div{ width:400px; border: 1px solid #000; height:400px; margin:50px auto; } ul{ list-style:none; } </style> </head> <body> <div> <ul> <li>0</li> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> </ul> </div> </body> </html> <script src="js/jquery-1.12.4.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div>ul>li').each(function(i){ console.log(i); }) </script>
第二种:
$('div').each(function (index,domEle){
index就是索引值
domEle 表示获取遍历每一个dom对象 //当前被选中的元素(也可以用this代替),如果用this代替,可以不写这个参数。
});
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style type="text/css"> div{ width:550px; border:1px solid #000; overflow: hidden; } div p{ width:100px; height:100px; background: red; float:left; margin-right:10px; } </style> </head> <body> <div> <p>0</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </div> <div> <p>0</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </div> <div> <p>0</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> </div> </body> </html> <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $('div').each(function(index,ele){ $(this).children().eq(1).css('backgroundColor','pink'); }) </script>
二、遍历$.each() (对象遍历)
1)先获取某个集合对象
2)遍历集合对象的每一个元素
var d=$("div");
$.each(d,function (index,domEle){
d是要遍历的集合
index就是索引值
domEle 表示获取遍历每一个dom对象
});
$.each([{name:"vico",email:"skfj@162.com"},{name:"holly",email:"shanhu@163.com"}],function(index,ele){
alert('索引:'+index+'对应的值为:'+ele.name)
})
输出 vico holly
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
输出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:1 2 3 4 5