gpt4 book ai didi

javascript 过滤器方法不适用于 getElementsByName

转载 作者:行者123 更新时间:2023-11-29 18:17:31 25 4
gpt4 key购买 nike

为什么下面的代码不起作用(不执行警报)? custom_table是html中的一些文件上传字段,长度为10。

var custom_table=document.getElementsByName('custom_table');
var result = custom_table.filter( function (x) { return x.value });
alert(result.length);

如果我在下面的代码中用 names 替换 custom_table,它工作正常。

var names = new Array();
var object = { name : "Joe", value:20, email: "joe@hotmail.com"};

names.push(object);
object = { name : "Mike", value:50, email: "mike@hotmail.com"};
names.push(object);
object = { name : "Joe", value:45, email: "mike@hotmail.com"};
names.push(object);

谢谢。

最佳答案

getElementsByName 返回一个 HTMLCollection*,它不是数组。 filter() 仅适用于数组。您可以很容易地将它转储到一个数组中:

var elementCollection = document.getElementsByName('myname');
var elementArray = Array.prototype.slice.call(elementCollection, 0);
elementArray.filter(...); // this will now work

* 或 NodeList,取决于浏览器,虽然区别不是很重要

关于javascript 过滤器方法不适用于 getElementsByName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21790892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com