如何循環遍歷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 循環 (ES6)

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM