zoukankan      html  css  js  c++  java
  • document.querySelectorAll遍历(forEach小解)

    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")       

    });

  • 相关阅读:
    面向对象简述
    python面向对象
    Python中int()函数的用法浅析
    给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
    python中关于round函数的小坑
    Xmind8破解,以及相关的流程和破解包
    生成器和生成器表达式
    brush图标
    js声明全局变量的方式
    js修改全局变量
  • 原文地址:https://www.cnblogs.com/yanze/p/5988142.html
Copyright © 2011-2022 走看看