@H_403_0@本文实例讲述了原生JS实现循环Nodelist Dom列表的4种方式。分享给大家供大家参考,具体如下:
<div class="jb51code">
<pre class="brush:js;">
function $(id) {
return document.getElementById(id);
}
var _PAGE = {
timeListDom: $('timeList')
};
var spanDoms = _PAGE.timeListDom.querySelectorAll('span'),domLen = spanDoms.length;
// 第一种方式:原生for循环
for (var i = 0; i < domLen; i++) {
var v = spanDoms[i];
// do something you want deal with DOM
}
// 第二种方式:Array 的 forEach函数
Array.prototype.forEach.call(spanDoms,function(v) {
// do something you want deal with DOM
});
// 第三种方式:Array 的 forEach函数
[].forEach.call(spanDoms,function(el) {
// do something you want deal with DOM
el.classList.remove('active');
});
// 第四种方式:继承Array 的 forEach函数
NodeList.prototype.forEach = Array.prototype.forEach;
spanDoms.forEach(function(v) {
// do something you want deal with DOM
});