如何拦截由 JS 事件触发的表单提交(在普通 JS 中)?

How to intercept the form submission fired by JS event (in plain JS)?

great answer here 介绍了如何在表单上使用 addEventListener 拦截 SUBMIT。 只要通过提交按钮(或 ENTER)提交表单,它就很好用。

虽然像这样被解雇时它完全被忽略了:

document.getElementById('myform').submit();

你会如何拦截这样的电话?

示例如下:

<script>
function checkRegistration(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    return true;
}
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com" id='myform'>
    Write google to go to google..<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>
<a href="javascript:document.getElementById('myform').submit();">Ignore validation</a>

事件侦听器仅在 user action submits the form

时触发

document.getElementById('myform').addEventListener(
  "submit",
  function(e){
    e.preventDefault();
    console.log("not submitting form");
  }
);
//the following never triggers the event listener:
//
//document.getElementById('myform').submit();
<form id="myform">
  <input type="submit" >
</form>

解决方案可能是:

if(validation){
  myForm.submit();
}

我想我刚刚找到了您要搜索的内容。你应该直接设置动作让JS在提交时处理它。

function check(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    return true;
}
<form id="myform" action="javascript:check();">
    <input type="text" id="some_input">
    <input type="submit">
</form>
你也可以这样做:
<form ... action="javascript:function(){...}">

好的。这是一个可能的解决方案,它需要一些锤炼但可能有效:

这是您的样本:

<script>
function checkRegistration(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    return true;
}
</script>

html:

<form onsubmit="return checkRegistration()" method="get" action="http://google.com" id='myform'>
    Write google to go to google..<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>
<a href="javascript:document.getElementById('myform').submit();">Ignore validation</a>

这是开始捕获事件的算法。如果您以编程方式调用 form.submit ,而不是覆盖似乎被忽略的 onsubmit 事件,您必须覆盖表单的提交方法。

<script>
    //document.getElementById('myform').onsubmit = function() {alert('testing'); return false;}
  var form = document.getElementById('myform');

  // Store the original method
  var tmp = form.submit;

  // create an intercept and override the submit method for the form with it
  form.submit = function(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    // when happy with the validation, apply the old method to the form
    tmp.apply(form);
  }

</script>

我在本地机器上试过了,它似乎可以工作。现在您必须概括此算法以处理任意形式。这可能会解决您的问题。