利用forEach循环Dom元素…

本文介绍了一种使用JavaScript中的forEach方法来遍历DOM元素的方法,并提供了兼容IE8及以下版本的解决方案。

大家都知道forEach是循环数组用的,而且很方便,可以丢掉for循环了,但是它不能循环Dom元素。
其实我们可以利用call来完成forEach循环Dom;

假设有这样的HTML结构:

<ul class="box">
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
</ul>

点击上面的LI来输出自身的索引值,具体可看下面代码:

var arrLi = document.querySelector(".box").children;
Array.prototype.forEach.call(arrLi, function(ele, index) {
	ele.onclick = function() {
		alert(index)
	}
})

需要注意的是,在IE8及以下是不支持forEach的,所以我们需要做下兼容,使用以下方法:

// 兼容IE8以下浏览器方法:
if (!Array.prototype.forEach) {
	Array.prototype.forEach = function(fun) {
		for (var i = 0; i < this.length; i++) {
			if (i in this) {
				fun.call(arguments[1], this[i], i, this);
			}
		}
	};
}

转载于:https://www.cnblogs.com/jone-chen/p/5942086.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值