利用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);
			}
		}
	};
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM