如何通过单击链接使用 JavaScript 提交表单?

如何通过单击链接使用 JavaScript 提交表单?

问题描述:

我有一个链接而不是提交按钮:

Instead of a submit button I have a link:

<form>

  <a href="#"> submit </a>

</form>

我可以让它在点击时提交表单吗?

Can I make it submit the form when it is clicked?

最好的方法

最好的方法是插入一个合适的输入标签:

The best way

The best way is to insert an appropriate input tag:

<input type="submit" value="submit" />

最好的 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();
});

将后面的 JavaScript 代码包含在 DOMContentLoaded 事件中(对于 向后兼容性) 如果您还没有这样做:

Enclose the latter JavaScript code by an DOMContentLoaded event (choose only load for backward compatiblity) if you haven't already done so:

window.addEventListener("DOMContentLoaded", function () {
  var form = document.... // copy the last code block!
});

简单,不推荐的方式(前一个答案)

向链接添加onclick 属性,向表单添加id:

<form id="form-id">

  <a href="#" onclick="document.getElementById('form-id').submit();"> submit </a>

</form>

所有方式

无论您选择哪种方式,最终都会调用 formObject.submit()(其中 formObject

的 DOM 对象> 标签).

All ways

Whatever way you choose, you have call formObject.submit() eventually (where formObject is the DOM object of the <form> tag).

您还必须绑定这样一个调用 formObject.submit() 的事件处理程序,以便在用户单击特定链接或按钮时调用它.有两种方式:

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. There are two ways:

  • 推荐:将事件侦听器绑定到 DOM 对象.

  • Recommended: Bind an event listener to the DOM object.

// 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();
});

  • 不推荐: 插入内联 JavaScript.这种技术不值得推荐的原因有几个.一个主要论点是您将标记 (HTML) 与脚本 (JS) 混合在一起.代码变得无组织且难以维护.

  • Not recommended: Insert inline JavaScript. There are several reasons why this technique is not recommendable. One major argument is that you mix markup (HTML) with scripts (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>
    

  • 现在,您必须决定触发 submit() 调用的 UI 元素.

    Now, we come to the point at which you have to decide for the UI element which triggers the submit() call.

    1. 一个按钮

    1. A button

    <button>submit</button>
    

  • 一个链接

  • A link

    <a href="#">submit</a>
    

  • 应用上述技术以添加事件侦听器.

    Apply the aforementioned techniques in order to add an event listener.