我正在尝试遍历所有getElementsByTagName("input")
使用forEach重构的元素。有什么想法为什么在FF,Chrome或IE中不起作用?
<html>
<head>
</head>
<body>
<input type="text" value="" />
<input type="text" value="" />
<script>
function ShowResults(value, index, ar) {
alert(index);
}
var input = document.getElementsByTagName("input");
alert(input.length);
input.forEach(ShowResults);
</script>
</body>
</html>
您需要使用以下命令将节点列表转换为数组:
<html>
<head>
</head>
<body>
<input type="text" value="" />
<input type="text" value="" />
<script>
function ShowResults(value, index, ar) {
alert(index);
}
var input = document.getElementsByTagName("input");
var inputList = Array.prototype.slice.call(input);
alert(inputList.length);
inputList.forEach(ShowResults);
</script>
</body>
</html>
或用于循环。
for(let i = 0;i < input.length; i++)
{
ShowResults(input[i].value);
}
并将ShowResults函数更改为:
function ShowResults(value) {
alert(value);
}
为什么我们需要这样做?
JavaScript中的某些对象看起来像一个数组,但不是一个。这通常意味着它们具有索引访问权限和length属性,但是没有数组方法。示例包括特殊的变量参数,DOM节点列表和字符串。类似数组的对象和通用方法提供了处理类似数组的对象的技巧。资源
2019年10月7日更新
如今,您可以使用ES6[...inputList].forEach
或Array.from(inputList)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句