我试着做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我得到以下错误:
Uncaught TypeError: parent.children.forEach不是一个函数
即使父母。孩子的日志:
有什么问题吗?
注:这是一个JSFiddle。
我试着做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我得到以下错误:
Uncaught TypeError: parent.children.forEach不是一个函数
即使父母。孩子的日志:
有什么问题吗?
注:这是一个JSFiddle。
当前回答
使用JSON.parse ()
str_json = JSON.parse(array);
str_json.forEach(function (item, index) {
console.log(item);
});
其他回答
那是因为父母。children是一个NodeList,并且它不支持.forEach方法(因为NodeList是一个类似数组的结构,但不是数组),因此尝试先通过using将其转换为数组来调用它
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
使用JSON.parse ()
str_json = JSON.parse(array);
str_json.forEach(function (item, index) {
console.log(item);
});
的父母。Children不是数组。它是HTMLCollection,它没有forEach方法。您可以先将其转换为数组。例如在ES6中:
Array.from(parent.children).forEach(child => {
console.log(child)
});
或者使用展开运算符:
[...parent.children].forEach(function (child) {
console.log(child)
});
你可以检查你是否输入正确的forEach,如果你像在其他编程语言中那样输入forEach,它将不起作用。
如果你试图像这样循环一个NodeList:
const allParagraphs = document.querySelectorAll("p");
我强烈推荐这样循环:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
就我个人而言,我已经尝试了几种方法,但大多数都不工作,因为我想循环一个节点列表,但这一个工作起来像一个魅力,给它一个尝试!
NodeList不是数组,但我们使用Array将其视为数组。所以,您需要知道旧的浏览器不支持它!
需要更多关于NodeList的信息?请在MDN上阅读其文档。