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>
var arrLi = document.querySelector(".box").children;
Array.prototype.forEach.call(arrLi, function(ele, index) {
    ele.onclick = function() {
        alert(index)
    }
})
原文地址:https://www.cnblogs.com/wang715100018066/p/7146514.html