【问题标题】:Return false; does not work in jquery .each function返回假;在 jquery .each 函数中不起作用
【发布时间】:2019-03-25 19:38:55
【问题描述】:

在发布这个问题之前,我尝试了 StackOverflow,但没有找到答案。

所以,问题是,我有一个包含一些值的数组(假设为 4、6、7、8、10 等)。我使用jquery的.each函数来提示alert信息。但是我的代码给了我一条警告消息,将焦点放在所需的输入框上并提交表单并且不会“返回 false”。 我希望它在聚焦后返回 false。

$(document).on('keypress','#create_invoice',function(){
$.each(newArr, function( i, l ){
//alert( "Index #" + i + ": " + l );
if($.trim($('#item_name'+l).val()).length == 0)
        {
          alert("Please Enter Item Name");
          $('#item_name'+l).focus();
         // return false; //if use this not work and submit form
        }
//return false; //if use this not work and submit form
});
//return false; if i use this then submit() not work
$('#invoice_form').submit();
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    返回 false 有效,但我认为您想要的是在返回 false 时阻止表单提交。这种行为可以用这个来完成;

    首先在函数参数中放入e,然后使用e.preventDefault();

    接下来是创建一个布尔变量,用于确定您是否可以允许表单提交。在下面的代码中,我使用了var allowSubmit

    试试下面的代码。

    $(document).on('keypress', '#create_invoice', function(e) {
      e.preventDefault();
    
      // boolean variable
      var allowSubmit = true;
    
      $.each(newArr, function(i, l) {
        if ($.trim($('#item_name' + l).val()).length == 0) {
          alert("Please Enter Item Name");
          $('#item_name' + l).focus();
    
          // set the variable to false
          allowSubmit = false;
          return false;
        }
      });
    
      // check if we could submit the form
      if (allowSubmit) {
        $('#invoice_form').submit();
      }
    });

    【讨论】:

    • 非常感谢,它对我有用,我删除了 if 条件之后的第二个“return false”,它在我的情况下工作正常。
    • 啊,是的!第一个return false; 足以停止循环。更新了答案以适应它。如果它是解决方案,请接受这个答案。谢谢。
    猜你喜欢
    • 2012-09-10
    • 2014-06-26
    • 2020-09-05
    • 2014-07-27
    • 2012-05-18
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    相关资源
    最近更新 更多