利用forEach循环Dom元素…

时间:2023-03-09 06:15:57
利用forEach循环Dom元素…

大家都知道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);
}
}
};
}

相关文章