使用document.getElementsByName()不起作用? [英] Using document.getElementsByName() isn't working?
本文介绍了使用document.getElementsByName()不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第二个警报命令的代码按预期工作(显示元素to的值,但是第一个警告命令不起作用(它应该做同样的事情)。为什么会这样?
The code for the second alert command works as intended (displaying the value of the element "to", but the first alert command does not work (it's supposed to do the same thing). Why is this?
<html>
<head>
<script type="text/javascript">
function getValue()
{
alert(document.getElementsByName("to").value);
alert(document.forms[0].to.value);
}
</script>
</head>
<body>
<form>
<input name="to" type="hidden" value="hoolah" />
<input type="button" onclick="getValue()" value="Get Value!" />
<form/>
</body>
</html>
推荐答案
getElementsByName
返回 HTMLCollection
。您可以像下面这样访问第一项的值:
getElementsByName
returns an HTMLCollection
. You can access the value of the first item like this:
document.getElementsByName("to").item(0).value
或者像这样:
document.getElementsByName("to")[0].value
更多信息:
- https://developer.mozilla.org/en/DOM/HTMLCollection
这篇关于使用document.getElementsByName()不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文