我在下面提到了我的代码,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/