zoukankan      html  css  js  c++  java
  • 如何循环遍历document.querySelectorAll()方法返回的结果

    使用JavaScript的forEach方法,我们可以轻松的循环一个数组,但如果你认为document.querySelectorAll()方法返回的应该是个数组,而使用forEach循环它:

    /* Will Not Work */
    document.querySelectorAll('.module').forEach(function() {
      
    });
    

      

    执行上面的代码,你将会得到执行错误的异常信息。这是因为,document.querySelectorAll()返回的不是一个数组,而是一个NodeList

    对于一个NodeList,我们可以用下面的技巧来循环遍历它:

    var divs = document.querySelectorAll('div');
    
    [].forEach.call(divs, function(div) {
      // do whatever
      div.style.color = "red";
    });
    

      当然,我们也可以用最传统的方法遍历它:

    var divs = document.querySelectorAll('div'), i;
    
    for (i = 0; i < divs.length; ++i) {
      divs[i].style.color = "green";
    }
    

      还有一种更好的方法,就是自己写一个:

    // forEach method, could be shipped as part of an Object Literal/Module
    var forEach = function (array, callback, scope) {
      for (var i = 0; i < array.length; i++) {
        callback.call(scope, i, array[i]); // passes back stuff we need
      }
    };
    
    // 用法:
    // optionally change the scope as final parameter too, like ECMA5
    var myNodeList = document.querySelectorAll('li');
    forEach(myNodeList, function (index, value) {
      console.log(index, value); // passes index + value back!
    });
    

      还有一种语法:for..of 循环,但似乎只有Firefox支持:

    /* Be warned, this only works in Firefox */
    
    var divs = document.querySelectorAll('div );
    
    for (var div of divs) {
      div.style.color = "blue";
    }
    

      最后是一种不推荐的方法:给NodeList扩展一个forEach方法:

    NodeList.prototype.forEach = Array.prototype.forEach;
    
    var divs = document.querySelectorAll('div').forEach(function(el) {
      el.style.color = "orange";
    })
    

      

  • 相关阅读:
    Eclipse/MyEclipse 选择Android NDK目录时提示“Not a valid NDK directory”
    Eclipse更改颜色主题
    Android模拟器访问本机服务器
    DIV水平垂直居中的CSS兼容写法
    Python3中使用PyMySQL连接Mysql
    Windows7 IE11 F12控制台DOC资源管理器报错的问题解决方法
    Windows 7无法卸载及安装IE11的解决方法
    查看端口占用
    VS2010/VS2013中ashx代码折叠的问题
    手机页面关于头部固定定位与input出现的问题
  • 原文地址:https://www.cnblogs.com/xupeiyu/p/5067115.html
Copyright © 2011-2022 走看看