利用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