JavaScript 按名称获取元素 [英] JavaScript get element by name
本文介绍了JavaScript 按名称获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个函数:
function validate()
{
var acc = document.getElementsByName('acc').value;
var pass = document.getElementsByName('pass').value;
alert (acc);
}
还有这个 HTML 部分:
And this HTML part:
<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".
推荐答案
您看到该错误的原因是 document.getElementsByName
返回一个 NodeList
元素.并且元素的 NodeList
没有 .value
属性.
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("acc")[0].value
这篇关于JavaScript 按名称获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文