今天将和大家介绍的是我们jQuery中的each()函数的用法,它可以允许我们循环遍历不同的数据,比如数组或者对象。jQuery中each()函数是jQuery中最常用的函数之一,接下来在文章中将为大家详细介绍这一方法的使用。
【推荐课程:jQuery教程】
jQuery中的each()函数用于循环数据,类似于for each循环。所以我们可以使用它来循环来自相同选择器的多个DOM对象
each() 方法
为每个匹配元素规定要运行的函数。
$(selector).each(function(index,element))
function(index,element) :为每个匹配元素规定所运行的函数。
index : 选择器的 index 位置,获取索引值
element :当前的元素(也可使用 "this" 选择器)
当在each函数内部时,我们可以通过使用this关键字来访问当前元素,但是这个对象不是jQuery对象
$("a").each(function(){
$(this);
})获取循环的当前索引
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script src="jquery/jquery-1.12.4.js"></script>
<script>
$(function(){
$("li").each(function(i){
console.log(i);
})
})
</script>
</body>结果如下图:
循环数组:
可以使用它来遍历数组并获取索引值和在数组中的位置的值。
<script src="jquery/jquery-1.12.4.js"></script>
<script>
var array=['Chinese','Math','English']
$.each(array,function(index,value){
console.log(index+":"+value);
})
</script>结果如下图:
循环对象:
可以使用它来遍历对象并获取索引值和在对象中的位置的值。
<script src="jquery/jquery-1.12.4.js"></script>
<script>
var obj={
name:"张三",
age:"18",
subject:"English"
};
$.each(obj,function(index,value){
console.log("信息:"+index+":"+value);
})
</script>结果如下图:
总结:
Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务