无法通过在 javascript 中使用表单名称来获取表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3927250/
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
unable to get form elements by using form name in javascript
提问by bassnoodle
I am having an issue with accessing my form by it's name. When I use document.form[0].mylink.value it recognizes the value and outputs to the innerHTML that I specify. However, when I use document.myform.mylink.value it doesn't seem to recognize the form. I have tried this in chrome 6.0 and also firefox 3.6.3 and get the same result in both. I really need to be able to access my form values by using the form name (instead of document.form[0]), any ideas why document.myform.mylink.value doesn't work?
我在按名称访问我的表单时遇到问题。当我使用 document.form[0].mylink.value 时,它会识别值并输出到我指定的 innerHTML。但是,当我使用 document.myform.mylink.value 时,它似乎无法识别该表单。我已经在 chrome 6.0 和 firefox 3.6.3 中尝试过这个,并且在两者中都得到了相同的结果。我真的需要能够通过使用表单名称(而不是 document.form[0])来访问我的表单值,任何想法为什么 document.myform.mylink.value 不起作用?
<form name="myform">
<table>
<tr><td valign="middle" align="center">
<div id="textResponse"></div>
</td></tr>
<tr><td height="30" valign="middle" align="center">
<input name="mylink" value="Enter a URL" size="31" />
</td></tr>
<tr><td valign="top" align="center">
<a href="javascript:submitForm2();">Click</a>
</td></tr>
</table>
</form>
<script type="text/javascript">
function submitForm2(){
//This one does NOT work:
my_link = document.myform.mylink.value;
//This one also does NOT work:
//my_link = document.forms['myform'].mylink.value;
//This one works:
//my_link = document.forms[0].mylink.value;
document.getElementById("textResponse").innerHTML="<p>"+my_link+"</p>";
}
</script>
回答by scunliffe
Technically what you have should work ok... the full syntax below should also work:
从技术上讲,您所拥有的应该可以正常工作……下面的完整语法也应该可以工作:
var my_link = document.forms['myform'].elements['mylink'].value;
If by chance your variable in your "real" code is "mylink"
not"my_link"
you will get failures in IE as it will auto-reference the form element, not the value you are trying to extract.
如果您的“真实”代码中的变量碰巧"mylink"
不是,"my_link"
您将在 IE 中失败,因为它会自动引用表单元素,而不是您尝试提取的值。
That all said, your code as posted... works just fine in Firefox/IE(demo here: http://jsfiddle.net/Ymg8W/)
话虽如此,您发布的代码……在 Firefox/IE 中运行良好(此处演示:http: //jsfiddle.net/Ymg8W/)