错误 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:57:22  来源:igfitidea点击:

Error document.form is undefined in javascript

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 documentdoes not exist. You're probably confused with the document.formsHTML collection:

的表单属性document不存在。您可能对document.formsHTML 集合感到困惑:

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

documenthas a property formswhich 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.formis not standard as far as I know. document.forms(note the 's') is. Documents can have multiple forms.

document.form据我所知,这不是标准的。document.forms(注意“s”)是。文档可以有多种形式。