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