document.querySelectorAll兼容性良好,在之前的項目中就其遍歷方式出了錯誤,先做個小結:
1.for循環 傳統遍歷方法
for(var i= 0; i< document.querySelectopAll(".a").length; i ++){
document.querySelectopAll(".a")[i].style.color= "red";
}
2.forEach方法
forEach方法可以遍歷一個js數組
var arr= [1, 2, 3];
arr.forEach(arr, function(pre){})
兼容性: 均兼容,IE低版本不兼容,本人使用的是IE9
若不兼容,可手動擴展:
詳情:http://blog.csdn.net/oscar999/article/details/8671546
if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; // Hack to convert O.length to a UInt32 if ({}.toString.call(callback) != "[object Function]") { throw new TypeError(callback + " is not a function"); } if (thisArg) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; }
如果這樣使用:
document.querySelectorAll(".aa").forEach(function(){
console.log("1")
})
會報錯,應為document.querySelectorAll(".aa")是一個NodeList數組,不是一般js數組!
可以借助call來實現
[].forEach.call(document.querySelectorAll(".aa"), function(){
console.log("1")
});
