使用特定按钮提交表单

Sup*_*ion 5 html javascript forms jquery

我有一个包含许多表单的页面,每个表单可能有多个提交按钮,每个按钮都有一些onclick由 html 指定的操作“ ”。

我已经通过 jquery为提交按钮创建了处理程序onclick,这些按钮可以防止默认操作并执行一些工作,但随后我需要提交此表单。如果我只是模拟单击按钮 - 触发到onclick 的所有操作都会再次起作用。

关于它的任何想法?

抽象代码示例:

<form>
  <input type='submit' name='first_button' onclick='doSomething()'>
  <input type='submit' name='second_button' onclick='doSomethingElse()'>
<form>
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 0

就打电话吧referenceToFormElement.submit()

由于您的提交按钮没有值,因此您不必关心服务器知道单击了哪一个按钮,因此在使用 JS 提交表单时绕过它们就可以了。

document.querySelector("[name=first_button]").addEventListener('click', doSomething);
document.querySelector("[name=second_button]").addEventListener('click', doSomethingElse);

function doSomething(e) {
  var button = this;
  e.preventDefault();
  setTimeout(function() {
    alert("Submitting A!");
    button.form.submit();
  }, 1000);
}

function doSomethingElse(e) {
  var button = this;
  e.preventDefault();
  setTimeout(function() {
    alert("Submitting B!");
    button.form.submit();
  }, 1000);
}
Run Code Online (Sandbox Code Playgroud)
<form>
  <input type='submit' name='first_button'>
  <input type='submit' name='second_button'>
</form>

<p>(NB: This won't actually submit because it is on Stackoverflow: Blocked form submission to 'http://stacksnippets.net/js' because the form's frame is sandboxed and the 'allow-forms' permission is not set.)
Run Code Online (Sandbox Code Playgroud)