Javascript this.form 和 document.forms 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11042214/
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 04:11:26  来源:igfitidea点击:

Difference between this.form and document.forms

javascriptformsthisdocument

提问by W3Geek

Is there a difference between this.formand document.forms (document["forms"])or, are they similar?

this.formdocument.forms (document["forms"])或它们之间有区别吗?它们相似吗?

Here is the code I wrote to test the difference.

这是我编写的用于测试差异的代码。

<form name="myForm" id="myForm">
<input type="text" name="haha" id="myForm" value="laughable" onclick="alert(this.form.haha.value)" />
</form>

alert(document.forms.myForm.haha.value);

They both result in the same thing.

他们都导致同样的事情。

回答by gdoron is supporting Monica

this.formwill give you the form of the form element. (thisis the form element)

this.form会给你表单元素的形式。(this是表单元素)

The containing form element, if this element is in a form.

包含表单元素,如果此元素在表单中。

document.formswill give you all the forms in the document (if it's supported!)

document.forms将为您提供文档中的所有表格(如果支持!)

forms returns a collection (an HTMLCollection ) of the form elements within the current document.

forms 返回当前文档中表单元素的集合(一个 HTMLCollection )。

Better use document.getElementById(id)

更好的使用 document.getElementById(id)

var form = document.getElementById(formId);

回答by SteveInMalvern

this.formwill return the form property of this, as noted above whatever "this"is.

this.form将返回 this 的 form 属性,如上所述,无论"this"是什么。

"this"could be anything, eg. a div, so possibly doesn't have a form property.

"this"可以是任何东西,例如。一个 div,所以可能没有表单属性。

If "this"happens to refer to document, then this.formwill return exactly the same thing as document.form. But otherwise, don't count on it.

如果"this"碰巧引用了文档,那么this.form将返回与document.form. 但否则,不要指望它。