简体   繁体   English

this.form和document.forms之间的区别

[英]Difference between this.form and document.forms

Is there a difference between this.form and 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. 他们都导致了同样的事情。

this.form will give you the form of the form element. this.form将为您提供表单元素的形式。 ( this is the form element) this是表单元素)

The containing form element, if this element is in a form. 包含表单元素,如果此元素是一个表单。

document.forms will give you all the forms in the document (if it's supported!) document.forms将为您提供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);

this.form will return the form property of this, as noted above whatever "this" is. this.form将返回this.form的form属性,如上所述,无论"this"是什么。

"this" could be anything, eg. "this"可以是任何东西,例如。 a div, so possibly doesn't have a form property. 一个div,所以可能没有表单属性。

If "this" happens to refer to document, then this.form will return exactly the same thing as document.form . 如果"this"碰巧引用了document,那么this.form将返回与document.form完全相同的东西。 But otherwise, don't count on it. 但除此之外,不要指望它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM