我试着做一个简单的循环:
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。
当前回答
因为你正在使用ES6的特性(箭头函数),你也可以简单地使用这样的for循环:
(让孩子({0:[{“a”:1、“b”:2},{' c ': 3}]}, {1: []})) { console.log(孩子) }
其他回答
那是因为父母。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将返回一个节点列表列表,技术上是一个html集合。这是一个类似于object的数组,但不是数组,所以你不能直接在它上面调用数组函数。在这种情况下,你可以使用array .from()将其转换为一个真正的数组,
Array.from(parent.children).forEach(child => {
console.log(child)
})
的父母。Children不是数组。它是HTMLCollection,它没有forEach方法。您可以先将其转换为数组。例如在ES6中:
Array.from(parent.children).forEach(child => {
console.log(child)
});
或者使用展开运算符:
[...parent.children].forEach(function (child) {
console.log(child)
});
你可以使用childNodes而不是child,考虑到浏览器兼容性问题,childNodes也更可靠,更多信息在这里:
parent.childNodes.forEach(function (child) {
console.log(child)
});
或者使用展开运算符:
[...parent.children].forEach(function (child) {
console.log(child)
});