javascript - 如何在表单元素上使用 map 方法
问题描述
我想创建一个表单元素的所有名称的列表。但是使用以下代码我得到了错误:“inputs.map 不是函数”
我知道这inputs
不是一个数组,但是我不确定如何让 this.map
起作用?
function process(form) {
console.dir(form)
var inputs = form.elements
for (let i = 0; i < inputs.length; i++) {
console.log(i+':'+inputs[i].name+': '+inputs[i].value);
}
let names = inputs.map( e => e.name )
console.log(names)
}
<form name=form1 method=none>
firstname: <input name=lastn value="a" type=text>
<br>lastname: <input name=firstn value="b" type=text>
<br>zipcode: <input name=zip value="c" type=text>
<br>ip: <input name=ip value="127.0.0.1" type=text disabled>
<br><input onclick="process(this.parentNode)" name=button type=button value="register">
</form>
顺便说一句,要运行代码,您必须单击“注册”按钮(因为它是“onclick”调用)
解决方案
HTMLFormElement.elements
是一个HTMLFormControlsCollection
,它是一个类似对象的数组,而不是一个实际的数组。使用以下方法将其转换为数组Array.from()
:
function process(form) {
var inputs = Array.from(form.elements)
const names = inputs.map(e => e.name)
console.log(names)
}
<form name=form1 method=none>
firstname: <input name=lastn value="a" type=text>
<br>lastname: <input name=firstn value="b" type=text>
<br>zipcode: <input name=zip value="c" type=text>
<br>ip: <input name=ip value="127.0.0.1" type=text disabled>
<br><input onclick="process(this.parentNode)" name=button type=button value="register">
</form>
推荐阅读
- drupal - 如何配对 DDEV 数据库以从 Drupal 7 迁移到 Drupal 8
- html - 如何隐藏视频控件
- javascript - 单击并返回下一步更改 div 阴影
- java - 如何找到我的数据库 url 以连接到 postgres?
- python - TypeError:元组索引必须是整数或切片,而不是 str scipy.optimize
- android - Android JSON 数组计数
- javascript - 使用 Winston Logger 登录 /var/log 失败
- scala - 荷兰国旗问题的惯用 Scala 解决方案
- twitter - 使用 twitter 应用程序登录时未执行 TWTRLogInCompletion 块
- google-cloud-platform - 如何在 GCP 上的 Dataproc 集群上安装 presto-admin?