Javascript 使用 document.getElementsByName() 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8845886/
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
Using document.getElementsByName() isn't working?
提问by user1146930
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?
第二个警报命令的代码按预期工作(显示元素“to”的值,但第一个警报命令不起作用(它应该做同样的事情)。这是为什么?
<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>
回答by Wayne
getElementsByName
returns an HTMLCollection
. You can access the value of the first item like this:
getElementsByName
返回一个HTMLCollection
. 您可以像这样访问第一项的值:
document.getElementsByName("to").item(0).value
Or like this:
或者像这样:
document.getElementsByName("to")[0].value
More info:
更多信息:
回答by James Montagne
getElementsByName
returns all elements with the given name. This means there can be more than one.
getElementsByName
返回具有给定名称的所有元素。这意味着可以有多个。
If you want to get the value of the first element:
如果要获取第一个元素的值:
document.getElementsByName("to")[0].value
回答by Jeff Wooden
That's because it puts the element(s) into an array, try this example instead:
那是因为它将元素放入数组中,请尝试以下示例:
function getValues(objName)
{
var arr = new Array();
arr = document.getElementsByName(objName);
alert("total objects with name \"textfield\" = \n" + arr.length);
for(var i = 0; i < arr.length; i++)
{
var obj = document.getElementsByName(objName).item(i);
alert(obj.id + " = " + obj.value);
}
}