jquery each 方法的参数

本文详细对比了原生JavaScript的forEach方法与jQuery中的$.each()及$().each()方法在遍历数组和DOM元素时的参数差异及使用场景,通过实例演示了如何在实际项目中灵活运用这些遍历技巧。

注意:
1.jquery中不管是 $().each(function(index,value){})还是$.each(arr,function(index,value){})
自定义函数的,第一个参数都是index , 第二个参数value.

2.原生js中的forEach(function(value,index,arr){})  
自定义函数的,第一个参数都是value,   第二个参数index .

1.forEach是js中遍历数组的方法



var arr=[1,2,3,4];

arr.forEach(function(val,index,arr){//val为数组中当前的值,index为当前值的下表,arr为原数组
    arr[index]=2*val;
});
console.log(arr);//结果是修改了原数组,为每个数乘以2

2.$.each()是jquery中遍历数组的方法

var arr=[1,2,3,4];
$.each(arr,function(i,n){
    alert("索引"+i+"对应的值"+n);
});

 

3.$().each()方法规定为每个匹配元素规定运行的函数 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试 jquer each的参数值</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
	$("button").click(function(){
		$("li").each(function(index,value){

            // 这是索引
			console.log('index>>',index)  
            
            // 这是dom元素
			console.log('value>>',value)

            // 这是jquery当前对象
			console.log('$this>>',$(this))

            // 这也是jquery当前对象注意看这个和上面这个是一样的
			console.log('$value>>',$(value))

			alert($(this).text())
		});
	});
});
</script>
</head>
<body>

<button>输出每个列表项的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>

</body>
</html>

 jquery 的 each方法参数测试结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宝码香车

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值