3

我基本上是在尝试进行表单验证。Evertyhing 工作正常。除了一件事。首先,这是我的代码:

        $('#submit_btn').click(function(){  

        $("input:not([type=radio],[type=checkbox])").each(function() {
                if ($(this).val() == ""){
                 $('#'+$(this).attr("name")+'_error').show("");
                }
                else{
                   $('#'+$(this).attr("name")+'_error').hide("normal");
                }

            });
            if(!($("div[id$=error]").is(":visible")))
                               alert("a");

        });

单击提交按钮后,它会检查不是单选按钮或复选框的输入。如果输入为空,则显示错误。

如果输入了一些输入,错误就会被隐藏。

最后我检查是否有任何错误消息可见,如果没有,我将提交表单。

我的问题是,我用 .hide("normal") 的小动画隐藏了错误消息。所以我相信在隐藏最后一个错误消息的过程中,我的最后一个 if 语句执行并且它认为有一个可见的错误消息(但是,它正在隐藏过程中)

隐藏过程完成后如何执行 if 语句?

就我而言,当没有留下错误消息时,我会在再次单击提交按钮后收到警报。

我希望我清楚我的问题。如果没有,我会尝试重写它。

谢谢!

4

2 回答 2

5

这样做:visible有点笨拙,而且肯定很慢。改用变量:

$('#submit_btn').click(function(){  
    var error = false;

    $("input:not([type=radio],[type=checkbox])").each(function() {
        if ($(this).val() == ""){
            $('#'+$(this).attr("name")+'_error').show(400);
            error = true;
        }
        else{
            $('#'+$(this).attr("name")+'_error').hide(400);
        }
    });
    if(error)
        alert("a");

});
于 2011-01-21T15:12:09.073 回答
0

如果您的目标是在函数完成动画后显示警报消息,.hide("normal")那么您需要将“回调”函数作为参数传递给.hide()函数。请参阅文档

在此处查看示例:

$('#submit_btn').click(function(){  
  $("input:not([type=radio],[type=checkbox])").each(function() {
    if ($(this).val() == ""){
      $('#'+$(this).attr("name")+'_error').show("");
    }
    else{
      $('#'+$(this).attr("name")+'_error').hide("normal", function() {

        // This function will be executed when the "normal" animation is complete

        if(!($("div[id$=error]").is(":visible")))
          alert("a");

      });
    }
  });
});

我的 2 美分... 不过,我会说,您可能想听听每个人的鼓励,寻求一个优雅的表单验证插件。

于 2011-01-21T15:16:19.687 回答