简体   繁体   English

onclick =“ document.forms [0] .submit();”和表单提交之间的区别

[英]Difference between onclick=“document.forms[0].submit();” and form submit

Inside a form I have a button. 在表单中,我有一个按钮。 What is the difference between when I submit the form via JavaScript like this 像这样通过JavaScript提交表单之间有什么区别

<button onclick="document.forms[0].submit();">

and when I submit it like this 当我这样提交时

<button type="submit"></button>?

The first one works for me with most browsers except webkit-based. 除基于Webkit的浏览器外,第一个适用于我的大多数浏览器。 The latter works fine as well. 后者也可以正常工作。 No difference in functionality is apparent to me. 功能上的差异对我而言并不明显。 Is there one? 有一个吗?

The first example: 第一个例子:

<button onclick="document.forms[0].submit();">

...will do two things: ...将做两件事:

  1. Its onclick will submit the first form in the document (ie, the one specified by the 0 index in forms[0] ). onclick将提交文档中的第一个表单(即,由forms[0]的0索引指定的forms[0] )。
  2. It will submit the form it is in (if it is in a form) because a button with no type attribute specified will be a submit button by default. 它将提交其所在的表单(如果在表单中),因为默认情况下,未指定type属性的按钮将是一个提交按钮。

This two-step double-submit behaviour can be seen in this quick-and-dirty demo: http://jsfiddle.net/fMwuX/ (and is likely to lead to weird behaviour that might be a bit confusing to debug). 在这个快速且肮脏的演示中可以看到这种两步两次提交的行为: http : //jsfiddle.net/fMwuX/ (并且可能导致奇怪的行为,可能会使调试有些混乱)。 If the button isn't actually in a form then this won't be a problem. 如果按钮实际上不是表单,则不会有问题。

The second example: 第二个例子:

<button type="submit"></button>

Will simply submit the form it is in (if it is in one). 只需提交它所在的表格(如果它在一个表格中)。

In my opinion the second option is definitely preferable for several reasons, including but not limited to: 我认为第二种选择绝对是可取的,原因有几个,其中包括但不限于:

  1. It will work even if the user has JS disabled. 即使用户禁用了JS,它也将起作用。
  2. It doesn't hard-code a form index with forms[0] . 它不会使用forms[0]对表单索引进行硬编码。
  3. It is shorter and clearer. 它更短更清晰。
  4. It won't clash with other form submit validation. 它不会与其他表单提交验证冲突。

javascript示例将提交HTML文档中的第一个表单,而第二个示例将提交包装该按钮的表单。

documents.forms[0].submit will trigger the submission of the first form in your HTML page. documents.forms[0].submit将触发您的HTML页面中第一个表单的提交。 Indeed, documents.forms contains all the forms of your document. 实际上, documents.forms包含documents.forms所有表单。 You can access them with their name attribute or their index. 您可以使用它们的名称属性或索引来访问它们。

Then, the input of type submit in a form will trigger the submission of his parent form. 然后,在表单中submit类型的输入将触发其父表单的提交。

As you've discovered, the first one makes the page not work in some circumstances, and is - for this, and other reasons - generally considered bad practice. 正如您所发现的,第一个使该页面在某些情况下不起作用,并且-由于这个原因和其他原因-通常被认为是不好的做法。 Use the second. 使用第二个。

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

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