返回 false;不适用于每个功能

标签 javascript jquery

我在下面提到了我的代码,return flase 有问题;在 javascript 中每个函数

$(".current_patient_medicine").each(function (i) {
    var id = this.id;
    var value = $("#" + id).val();
    if (value.trim() == "") {

        check = false;
        alert("Medicine Name cannot left Blank.");
        return false;
    } else {
        check = true;
    }
});
$(".current_patient_medicine_days").each(function (i) {
    var id = this.id;
    var value = $("#" + id).val();
    if (value.trim() == "") {

        check = false;
        alert("Days Field cannot left Blank.");
        return false;
    } else {
        check = true;
    }
});

这里第一个条件警报“药物名称不能留空”显示良好,但之后第二个警报也显示

最佳答案

你在内部函数调用中有return false,它不会停止外部函数的执行流程,所以你需要

var check = true;
$(".current_patient_medicine").each(function (i) {
    var value = this.value;
    if (value.trim() == "") {
        check = false;
        alert("Medicine Name cannot left Blank.");
        return false;
    }
});
if (!check) {
    return false;
}
$(".current_patient_medicine_days").each(function (i) {
    var value = this.value;
    if (value.trim() == "") {
        check = false;
        alert("Days Field cannot left Blank.");
        return false;
    }
});
if (!check) {
    return false;
}

$('button').click(function() {
  var check = true;
  $(".current_patient_medicine").each(function(i) {
    var value = this.value;
    if (value.trim() == "") {
      check = false;
      alert("Medicine Name cannot left Blank.");
      return false;
    }
  });
  if (!check) {
    return false;
  }
  $(".current_patient_medicine_days").each(function(i) {
    var value = this.value;
    if (value.trim() == "") {
      check = false;
      alert("Days Field cannot left Blank.");
      return false;
    }
  });
  if (!check) {
    return false;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="m1" class="current_patient_medicine" />
<input id="d1" class="current_patient_medicine_days" />
<br />
<input id="m2" class="current_patient_medicine" />
<input id="d2" class="current_patient_medicine_days" />
<br />
<button>Test</button>

关于返回 false;不适用于每个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556372/

相关文章:

javascript - 如何使用 JavaScript 和 HTML 组合框 (<select>) 加载文本文件?

javascript - 如何使用 Javascript 在不同月份的日历中突出显示多个日期?

javascript - Vue.js 可以在用户输入数字时添加逗号吗?

jquery - 在输入的字段下设置动态创建的自动完成建议位置

php - 如何连续显示元素(即每行 5 个元素)

javascript - 如何在 Google Apps 脚本上请求 Reddit 的访问 token

javascript - innerHTML 写在 div 中

javascript - 在javascript ES6中寻找更高效的排序算法

javascript - 使用 jQuery 扩展 div 时浏览器滚动

javascript - 嵌套的 ng-binding 与 angularJS