Difference between this.form and document.forms

自古美人都是妖i 提交于 2019-12-23 12:16:33

问题


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

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.


回答1:


this.form will give you the form of the form element. (this is the form element)

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!)

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

Better use document.getElementById(id)

var form = document.getElementById(formId);



回答2:


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

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

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



来源:https://stackoverflow.com/questions/11042214/difference-between-this-form-and-document-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!