如何循环遍历document.querySelectorAll()方法返回的结果
生活随笔
收集整理的這篇文章主要介紹了
如何循环遍历document.querySelectorAll()方法返回的结果
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用JavaScript的forEach方法,我們可以輕松的循環(huán)一個(gè)數(shù)組,但如果你認(rèn)為document.querySelectorAll()方法返回的應(yīng)該是個(gè)數(shù)組,而使用forEach循環(huán)它:
/* Will Not Work */ document.querySelectorAll('.module').forEach(function() {});
執(zhí)行上面的代碼,你將會(huì)得到執(zhí)行錯(cuò)誤的異常信息。這是因?yàn)?#xff0c;document.querySelectorAll()返回的不是一個(gè)數(shù)組,而是一個(gè)NodeList。
對(duì)于一個(gè)NodeList,我們可以用下面的技巧來循環(huán)遍歷它:
var divs = document.querySelectorAll('div');[].forEach.call(divs, function(div) {// do whateverdiv.style.color = "red"; });當(dāng)然,我們也可以用最傳統(tǒng)的方法遍歷它:
var divs = document.querySelectorAll('div'), i;for (i = 0; i < divs.length; ++i) {divs[i].style.color = "green"; }還有一種更好的方法,就是自己寫一個(gè):
?
// 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! });還有一種語(yǔ)法:for..of?循環(huán),但似乎只有Firefox支持:
/* Be warned, this only works in Firefox */var divs = document.querySelectorAll('div );for (var div of divs) {div.style.color = "blue"; }最后是一種不推薦的方法:給NodeList擴(kuò)展一個(gè)forEach方法:
NodeList.prototype.forEach = Array.prototype.forEach;var divs = document.querySelectorAll('div').forEach(function(el) {el.style.color = "orange"; })
轉(zhuǎn)載于:https://www.cnblogs.com/xupeiyu/p/5067115.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的如何循环遍历document.querySelectorAll()方法返回的结果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VHDL基本门电路和数值比较器的设计
- 下一篇: VHDL简易电子琴的设计