The best way(最好的方法)
The best way is to insert an appropriate input tag:
(最好的方法是插入适当的输入标记:)
<input type="submit" value="submit" />
The best JS way(最好的JS方式)
<form id="form-id">
<button id="your-id">submit</button>
</form>
var form = document.getElementById("form-id");
document.getElementById("your-id").addEventListener("click", function () {
form.submit();
});
Enclose the latter JavaScript code by an DOMContentLoaded
event (choose only load
for backward compatiblity ) if you haven't already done so:
(如果您还没有这样做,请将DOMContentLoaded
事件包含在后面的JavaScript代码中(仅为向后兼容性选择load
):)
window.addEventListener("DOMContentLoaded", function () {
var form = document.... // copy the last code block!
});
The easy, not recommandable way (the former answer)(简单,不可推荐的方式(前一个答案))
Add an onclick
attribute to the link and an id
to the form:
(向链接添加onclick
属性并向表单添加id
:)
<form id="form-id">
<a href="#" onclick="document.getElementById('form-id').submit();"> submit </a>
</form>
All ways(各方面)
Whatever way you choose, you have call formObject.submit()
eventually (where formObject
is the DOM object of the <form>
tag).
(无论选择何种方式,最终都会调用formObject.submit()
(其中formObject
是<form>
标记的DOM对象)。)
You also have to bind such an event handler, which calls formObject.submit()
, so it gets called when the user clicked a specific link or button.
(您还必须绑定这样一个调用formObject.submit()
的事件处理程序,以便在用户单击特定链接或按钮时调用它。)
There are two ways:(有两种方法:)
Recommended: Bind an event listener to the DOM object.
(推荐:将事件侦听器绑定到DOM对象。)
// 1. Acquire a reference to our <form>. // This can also be done by setting <form name="blub">: // var form = document.forms.blub; var form = document.getElementById("form-id"); // 2. Get a reference to our preferred element (link/button, see below) and // add an event listener for the "click" event. document.getElementById("your-id").addEventListener("click", function () { form.submit(); });
Not recommended: Insert inline JavaScript.
(不推荐:插入内联JavaScript。)
There are several reasons why this technique is not recommendable.(有几个原因导致这种技术不值得推荐。)
One major argument is that you mix markup (HTML) with scripts (JS).(一个主要的争论是你将标记(HTML)与脚本(JS)混合在一起。)
The code becomes unorganized and rather unmaintainable.(代码变得无组织且无法维护。)
<a href="#" onclick="document.getElementById('form-id').submit();">submit</a> <button onclick="document.getElementById('form-id').submit();">submit</button>
Now, we come to the point at which you have to decide for the UI element which triggers the submit() call.
(现在,我们来讨论触发submit()调用的UI元素。)
A button
(一个按钮)
<button>submit</button>
A link
(一条链接)
<a href="#">submit</a>
Apply the aforementioned techniques in order to add an event listener.
(应用上述技术以添加事件侦听器。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…