我的if else语句仅检查第一个?任何人都知道为什么它不检查其余条件吗?-跳过其余条件。我设置了3个变量来简化条件的编写。以下是HTML和JQUERY
<select id="tToth">
<option value="0">Select a state</option>
<option value="1">California</option>
<option value="2">Colorado</option>
</select>
<br>
<br>
<select id="tState">
<option value="0">Select a Zone</option>
<option value="1">west</option>
<option value="2">sout</option>
<option value="3">east</option>
</select>
<br>
<br>
<input type="text" id="boxa" size="6" required="required"></input>
<br>
<br>
<input type="text" id="boxb" size="6" required="required"></input>
<br>
<br>
<input type="text" id="boxb" size="6" required="required"></input>
<br>
<br>
<input type="button" id="answerButton" value="Get Answer"></input>
var plate = $("#tToth").val();
var bowl = $("#tState").val();
var emptyTextBoxes = $('input:text').filter(function () {
return this.value === "";
});
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function () {
string += "\n" + this.id;
});
if (emptyTextBoxes && plate && bowl) {
alert("empty boxes and plate & bowl");
$(".error").show();
} else if (emptyTextBoxes && !plate && !bowl) {
alert("empty boxes, plate and bowl");
$(".error").show();
} else if (!emptyTextBoxes && plate && !bowl) {
alert("nothing empty");
$(".error").show();
}
很难确切地说出您要问什么问题,但是如果您是否进行其他测试,则有几处错误,因此我将为您解释,也许也可以解释不适用于您的问题。
首先,emptyTextBoxes
是一个jQuery对象,而对象始终是真实的。这意味着您永远不会满足您的最后一个条件,因为!emptyTextBoxes
永远不会是真实的。
如果要测试以查看jQuery对象是否为空(例如,其中没有DOM元素),则应进行检查emptyTextBoxes.length
。
因此,仅修复if / else的那一部分,您将拥有以下功能:
// if we have some emptyTextBoxes, but we do have values for plate and bowl
if (emptyTextBoxes.length && plate && bowl) {
alert("empty boxes and plate & bowl");
$(".error").show();
// if we have emptyTextBoxes, but no values for plate and bowl
} else if (emptyTextBoxes.length && !plate && !bowl) {
alert("empty boxes, plate and bowl");
$(".error").show();
// there are no empty text boxes, we have plate, but not bowl
} else if (!emptyTextBoxes.length && plate && !bowl) {
alert("nothing empty");
$(".error").show();
}
除此之外,您可能会遇到逻辑错误,因为您没有涵盖所有可能的条件,并且某些条件将不符合您的条件,并且不清楚您的测试是否在为您提供所需的条件。我已经为每个条件添加了注释,以说明它正在测试什么条件。
特别地,似乎最后一个条件可能永远不会满足,因为如果plate
和bowl
是<input>
字段,则不可能为零emptyTextBoxes
,而是bowl
要为空,因为如果bowl
为空,则其中emptyTextBoxes
将包含某些内容。
如果您需要进一步的帮助来整理这些if / else条件的逻辑,那么您将需要用言语解释每个if
条件要匹配的内容,我们将为您提供适当的逻辑帮助。
根据您的进一步说明,下面是一个代码版本,可在单击“答案”按钮时检查每种输入类型:
$("#answerButton").click(function(e) {
var plate = $("#tToth").val();
var bowl = $("#tState").val();
var emptyTextBoxes = $('input:text').filter(function () {
return this.value === "";
});
if (plate === "0") {
alert("Please select a State");
} else if (bowl === "0") {
alert("Please select a Zone");
} else if (emptyTextBoxes.length !== 0) {
alert("All text fields must contain a value")
} else {
alert("All values good");
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句