错误 document.form 在 javascript 中未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8892631/
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
Error document.form is undefined in javascript
提问by Rob W
I have a code javascript:
我有一个代码javascript:
<form onsubmit="return false;" action="">
<input type="radio" name="type" id="type0" value="0" onclick="toggleSet(this)" checked />type 0
<input type="radio" name="type" id="type1" value="1" onclick="toggleSet(this)" />Type 1
</form>
<script>
function toggleSet() {
for(var i=0; i<document.form.type.length; i++) {
if(document.form.type[i].checked) {
var type = document.form.type[i].value;
}
}
alert(type);
}
</script>
ouput error: document.form is undefined, how to fix it ?
输出错误:document.form 未定义,如何解决?
回答by Rob W
The form property of document
does not exist. You're probably confused with the document.forms
HTML collection:
的表单属性document
不存在。您可能对document.forms
HTML 集合感到困惑:
document.forms[0]; //First <form> element
document.forms['name_of_form']; //Points to <form name="name_of_form">
Fixed code:
固定代码:
function toggleSet() {
var form = document.forms[0];
var type; //Declare variable here, to prevent a ReferenceError at the end
for(var i=0; i<form.type.length; i++) {
if(form.type[i].checked) {
type = form.type[i].value;
break; // After finding an occurrence, break the loop:
// You expect only one value
}
}
alert(type);
}
回答by Kingk
Just define the name to form like < form name="form1" ...> and call the form with the form name... that it :)
只需定义名称以形成像 <form name="form1" ...> 并使用表单名称调用表单...它:)
e.g var type = document.form1.type[i].value;
例如 var type = document.form1.type[i].value;
回答by Didier Ghys
There is no property document.form
.
没有财产document.form
。
document
has a property forms
which is an array of the forms the document contains. You access the desired form this way:
document
有一个属性forms
,它是文档包含的表单数组。您可以通过以下方式访问所需的表单:
document.forms[0] // first form
document.forms['theForm'] // form with name="theForm"
回答by sirlark
document.form
is not standard as far as I know. document.forms
(note the 's') is. Documents can have multiple forms.
document.form
据我所知,这不是标准的。document.forms
(注意“s”)是。文档可以有多种形式。