上篇说了$.each()的用法,那么整理一下jquery的each()方法,便于新手区分二者区别。

each方法 - 将页面符合条件的元素,依次执行某个函数。

$('p').each(function(index,element))

index - 选择器的序列位置(从0开始),页面中第n+1个元素;
element - 当前的元素
回顾jquery的each()方法-QUI-Notes

each案例

1.分别打印一下index,element,看看二者分别是什么内容;

let a = [];
list();
function list(){
       $(".box p").each(function(index,item){
  console.log("index:"+index)  // 0...
  console.log("item:"+item)  // [object HTMLParagraphElement]
        })
}

回顾jquery的each()方法-QUI-Notes

2.将所有p的内容添加到一个数组里面(练习)

let a = [];
list();
function list(){
$(".box p").each(function(index,item){
a.push($(this).text());
})
    log(a)
}
function log(val){
  console.log(val) //  Array(6) 0: "1" ......
 }

回顾jquery的each()方法-QUI-Notes