jQuery javascript未正确返回true/false

jQuery javascript not returning true/false properly

本文关键字:true false 返回 javascript jQuery      更新时间:2023-09-26

我编写这段代码是为了在提交表单之前显示提示。如果表单输入的值大于100,则会显示一个对话框,大致通知用户处理所需的时间。如果他们点击"确定",它应该返回true,并提交表格,如果他们点击取消,它应该回复false,并不提交表格。

问题是,表单没有等待这个响应,它无论如何都在提交。我不知道怎么了。。。

这是代码:

$(document).ready(function() {
  $("form#generate_vouchers").submit(function(){
    if($("input#quantity").val() > 100){
        var warning = "It will take around " + Math.round(($("input#quantity").val() / 23)) + " seconds to generate this batch.<br />Generation will continue even if you leave this page.";
        //Does around 23 codes per second, nearly all of that time is inserts.
        $('<div title="Batch information"></div>').html(warning).dialog({
            draggable: false,
            modal: true,
            minWidth: 350,
            buttons: {
                "Cancel" : function() {
                    $(this).dialog("close");
                    return false;
                },
                "Yes": function() {
                    $("input#submit").hide(300, function(){
                        $("img#loader").show(300);
                    });
                    return true;
                }
            }
        });
    }
    else{
        $("input#submit").hide(300, function(){
            $("img#loader").show(300);
        });
    }
  });
 });

显示对话不会停止执行并等待它关闭。提交功能继续,return truereturn false不执行任何操作。

您需要做的是立即停止表单提交(使用下面的e.PreventDefault),然后在Yes回调中再次提交表单。

$("form#generate_vouchers").submit(function(e){
if($("input#quantity").val() > 100){
    e.preventDefault(); // stop submit
    var warning = "It will take around " + Math.round(($("input#quantity").val() / 23)) + " seconds to generate this batch.<br />Generation will continue even if you leave this page.";
    //Does around 23 codes per second, nearly all of that time is inserts.
    $('<div title="Batch information"></div>').html(warning).dialog({
        draggable: false,
        modal: true,
        minWidth: 350,
        buttons: {
            "Cancel" : function() {
                $(this).dialog("close");
            },
            "Yes": function() {
                $("form#generate_vouchers")[0].submit(); // submit form manually
                $("input#submit").hide(300, function(){
                    $("img#loader").show(300);
                });
            }
        }
    });
}
else{
    $("input#submit").hide(300, function(){
        $("img#loader").show(300);
    });
}
});

示例-http://jsfiddle.net/infernalbadger/ajRr7/