简体   繁体   English

JavaScript onsubmit preventDefault无法有条件地工作

[英]JavaScript onsubmit preventDefault not working conditionally

If I use e.preventDefault() into onsubmit it is prevents form submission. 如果我在onsubmit使用e.preventDefault() ,则会阻止表单提交。 But if I use it conditionally it doesn't work. 但是,如果我有条件地使用它,它将无法正常工作。 See below code: 请参阅以下代码:

 var register = document.getElementById('registerForm'); register.onsubmit = function(e){ e.preventDefault(); //it is working } register.onsubmit = function(e){ if(5==5){ e.preventDefault(); // it is not working } } 
 <form action="#" id="registerForm"> <input type="text" id="username"> <input type="submit" id="submitBtn"> </form> 

That code's working fine. 该代码工作正常。 But, some other event is not allowing it to run. 但是,其他一些事件不允许它运行。 Could be some Console errors too. 也可能是某些控制台错误。 But, if you wanna break the flow, you can also do this: 但是,如果您想打破流程,也可以这样做:

register.onsubmit = function (e) {
  if (5 == 5) {
    return false;
  }
}

But remember, the above code will break all the further instructions attached to the particular event after this is executed. 但是请记住,上面的代码将在执行后破坏附加到特定事件的所有其他指令。

Try this. 尝试这个。 I use it in Nette Framework and it works. 我在Nette Framework中使用它,并且可以正常工作。 But you have to create "fake button" and hide the real submit button. 但是您必须创建“假按钮”并隐藏实际的提交按钮。 HTML: HTML:

<form method="post" id="registerForm">
    <input type="button" id="fakeSubmitButton" />
    <input type="submit" id="submit" style="visibility:hidden" />
<form>

JS: var register = document.getElementById('registerForm'); JS:var register = document.getElementById('registerForm'); var fakeBtn = document.getElementById('fakeSubmitBtn'); var fakeBtn = document.getElementById('fakeSubmitBtn');

fakeBtn.click(function(e) { //user clicks on the fake submit button
    if ( 5==5 ) {
        e.preventDefault();
    } else {
        register.submit(); //call submit on real submit button
    }
});

Why not debug by adding breakpoints if you think something is strange in those lines? 如果您认为断行有些奇怪,为什么不通过添加断点进行调试呢? Or put the code you are suspecting in try catch block and see if catch gets invoked. 或者将您怀疑的代码放在try catch块中,看看是否调用了catch。

Because 5==5 will always be true and that if condition doesn't makes a difference. 因为5 == 5将始终为true,并且条件不受影响。

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

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