您的位置:首页 > Web前端 > Node.js

从零开始学_JavaScript_系列(30)——NodeList

2016-10-13 20:09 477 查看
(48)NodeList的forEach

github连接:
https://github.com/qq20004604/some_demo/tree/master/NodeList
①首先,NodeList不是数组,因此,在某些版本浏览器里,是没有forEach方法的(具体而言,我在chrome50版本里遇见过这个问题);

 

NodeList可以通过querySelectorAll来获得。但注意,通过document.getElementsByClassName获得的并不是NodeList

console.log(document.getElementsByClassName("test") instanceof NodeList)


返回值是false

 

②NodeList是获取时决定的,而不是需要他时,实时生成,这点和数组类似,执行代码时确认

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script>
var nodeList = null;
function getList() {
nodeList = document.querySelectorAll(".test")
console.log(document.getElementsByClassName("test") instanceof NodeList)
console.log(nodeList instanceof NodeList)
}

function addTestNode() {
var parent = document.getElementById("list");
var node = document.createElement("p");
node.innerHTML = "test";
node.classList.add("test");
parent.appendChild(node);
}

if (!("forEach" in NodeList)) {
NodeList.prototype.forEach = Array.prototype.forEach;
}

function showNodeList() {
document.getElementById("log").innerHTML = JSON.stringify(nodeList.length);
console.log(nodeList);
}

</script>
<p>以下是NodeList的结点列表</p>
<div id="list">
</div>
<p>以下显示NodeList的当前数组元素数,console可以查看当前NodeList有哪些元素</p>
<div id="log">

</div>
<button onclick="getList()">获取list</button>
<button onclick="addTestNode()">添加结点</button>
<button onclick="showNodeList()">显示list</button>
</body>
</html>

③也就是①中所说,在某些低版本浏览器里,比如我发现在chrome 50这个版本的浏览器中,有querySelectorAll这个方法,但是这个方法获取的NodeList不存在forEach方法,如果使用则会报错,但是chrome51可以正常运行。

 

解决办法是查看NodeList是否有forEach方法,如果没有的话,则将Array数组的forEach方法提供给他。

if (!("forEach" in NodeList)) {
NodeList.prototype.forEach = Array.prototype.forEach;
}

但我查看某些文章说不推荐这个方法,至于原因我并不是很明白

也可以使用for循环,将其放入一个数组中来替代这个方法,然后使用数组的forEach方法来替代这个方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐