jQuery中的遍历
方法名:each()
基本语法:
$(‘选择器’).eac(function(index,element){});
function是方法,后边的是参数,根据需求定义相关的参数,以获取想要得到的遍历对象。
// 输出元素的内容
$('button').each(function(){// 不需要参数
console.log(this.innerHTML);// this是当前对象
})
// 遍历下标
$('button').each(function(index){
console.log(index);
})
// 遍历下标以及内容
$('button').each(function(index,element){
console.log(index,element.innerHTML);
})
除了遍历元素还可以遍历指定的集合数据
定义一个数组,将其遍历;
在each方法里面多了一个参数 不难看出参数一“arr”是要遍历的数组;参数二是函数,与前面相同的是 function里面的参数也是可以灵活变化的
let arr = ["李白","韩信","兰陵王"]
$.each(arr,function(index,element){
console.log(index,element)
})
遍历json,值得注意的是json是以键值对的形式存储数据的,所以遍历的结果是key和value
let json = {"name":'李白',"age":24};
$.each(json,function(key,val){
console.log(key,val);
})