return false在javascript对象中不起作用

时间:2016-07-22 03:50:11

标签: javascript jquery

我有2个警报();并尝试使用' return false'并期望它会奏效。

$(function() {
  var options = ['mandatory', 'email'];
  var validation_event = {
    mandatory: function(that) {
      if (!$(that).val() && $(that).data('placeholder')) {
        alert('Please fill in ' + $(that).data('placeholder') + '.');
        return false; // this is not working? I want to alert only one alert
      }
    }
  }

  function init() {
    $('input,select,textarea').each(function() {
      var self = $(this);

      $.each(options, function(i, val) {
        var attr = self.attr(val); // option array
        if (typeof attr !== typeof undefined && attr !== false) {
          validation_event[val](self);
        }
      });
    });
  }

  $('#submit').click(function(e) {
    e.preventDefault();
    init();
  })

})

尝试编写验证逻辑,每次都可以重用。

https://jsfiddle.net/m5jsscp7/

1 个答案:

答案 0 :(得分:1)

问题是,即使从验证函数返回false,每个循环也会继续运行。

如果验证失败,您可以从每个处理程序返回false以跳过进一步执行,如



$(function() {
  var options = ['mandatory', 'email'];
  var validation_event = {
    mandatory: function(that) {
      if (!$(that).val() && $(that).data('placeholder')) {
        alert('Please fill in ' + $(that).data('placeholder') + '.');
        return false; // this is not working? I want to alert only one alert
      }
      return true;
    },
    email: function() {
      return true;
    }
  }

  function init() {
    var valid = true;
    $('input,select,textarea').each(function() {
      var self = $(this);

      $.each(options, function(i, val) {
        var attr = self.attr(val); // option array
        if (typeof attr !== typeof undefined && attr !== false) {
          valid = validation_event[val](self) && valid;
        }
        return valid;
      });
    return valid;
    });
    return valid;
  }

  $('#submit').click(function(e) {
    e.preventDefault();
    console.log(init());
  })

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="fname" id="fname" mandatory data-placeholder="First Name">
<input data-placeholder="Email Address" type="text" id="email" mandatory email name="email" value="">
<button id="submit">Submit</button>
&#13;
&#13;
&#13;