jquery:防止默认浏览器表单提交行为,但使用 jquery 提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5081674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:32:12  来源:igfitidea点击:

jquery: prevent default browser form submit behaviour but submit form with jquery?

jqueryformssubmitform-submit

提问by matt

$('#search_form').submit(function(e) {
    //e.preventDefault();
    return false;
})

This works just fine to prevent form submission when pressing Enter.

这可以很好地防止按 Enter 时提交表单。

However even I have this I want to submit the form with jquery if certain circumstances are true.

但是,即使我有这个,如果某些情况属实,我也想用 jquery 提交表单。

edit:

编辑:

$('#search_form').submit(function(e) {
    return !!e.submit;
});

function ...

    if (e.keyCode == 13) {

        if (blablabla) {

            ... // do something

        } else {
            $('#search_form').submit({submit:true}); //doesn't work
            console.log('submitted'); //this does successfully get fired
        }

    }

If I press enter the form doesn't get submitted, but the log in in the console happens!

如果我按回车,表单不会被提交,但会在控制台中登录!

回答by Val

$('#search_form').submit(function(e) {
   if($('.errors').is(':visible')){
        e.preventDefault();
        // do something else here// some errors are visible :)
        return false; 
   }else{

   }
})

回答by signereign

By checking the type of e.originalEventwe can determine if human (type object) or script (type undefined) submitted the form:

通过检查的类型,e.originalEvent我们可以确定是人(类型对象)还是脚本(类型未定义)提交了表单:

$('#search_form').submit(function(e) {
    if (typeof e.originalEvent !== 'undefined') {
        e.preventDefault();
    }
})

Invoke a jquery trigger to submit the form:

调用一个 jquery 触发器来提交表单:

$('#search_form').trigger('submit');