JavaScript 按名称获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10306129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript get element by name
提问by Juliver Galleto
Consider this function:
考虑这个函数:
function validate()
{
var acc = document.getElementsByName('acc').value;
var pass = document.getElementsByName('pass').value;
alert (acc);
}
And this HTML part:
而这个 HTML 部分:
<table border="0" cellpadding="2" cellspacing="0" valign="top">
<tr>
<td class="td1">Account</td>
<td class="td2"><input type="text" name="acc" /></td>
</tr>
<tr class="td1">
<td>Password</td>
<td class="td2"><input type="password" name="pass" /></td>
</tr>
</table>
<div><button onClick="validate()" class="cupid-greenx">Login now</button></div>
The alert box is showing, but it shows "undefined".
警报框正在显示,但显示“未定义”。
回答by Aidanc
The reason you're seeing that error is because document.getElementsByName
returns a NodeList
of elements. And a NodeList
of elements does not have a .value
property.
您看到该错误的原因是document.getElementsByName
返回 a NodeList
of 元素。而 a NodeList
of 元素没有.value
属性。
Use this instead:
改用这个:
document.getElementsByName("acc")[0].value
回答by Ozzy
Note the plural in this method:
请注意此方法中的复数形式:
document.getElementsByName()
That returns an array of elements, so use [0] to get the first occurence, e.g.
这将返回一个元素数组,因此使用 [0] 来获取第一次出现,例如
document.getElementsByName()[0]
回答by Elliot Bonneville
You want this:
你要这个:
function validate() {
var acc = document.getElementsByName('acc')[0].value;
var pass = document.getElementsByName('pass')[0].value;
alert (acc);
}
回答by dalazx
Method document.getElementsByName returns an array of elements. You should select first, for example.
方法 document.getElementsByName 返回一个元素数组。例如,您应该首先选择。
document.getElementsByName('acc')[0].value
回答by Sam Battat
document.getElementsByName("myInput")[0].value;