复杂的if语句运行代码而不考虑条件输出

complex if statement runs code regardless of condition output

本文关键字:不考虑 条件 输出 代码 运行 if 语句 复杂      更新时间:2023-09-26

JS

if (isNaN(BDyear) == true || isNaN(BDmonth) == true || 
    isNaN(BDday) == true || BDday.length != 2 || 
    BDmonth.length != 2 || BDyear.length != 4)
{
    document.getElementById("BDyear").value = ''
    document.getElementById("BDmonth").value = ''
    document.getElementById("BDday").value = ''
    document.getElementById("bderror").style.display = "inline"
    BDstate = false BDcheck = false
}

HTML

<tr>
    <td>שנת לידה</td>
    <td>
        <input class="text" id="BDyear" maxlength="4" style="width:8%" />&nbsp/&nbsp
        <input class="text" id="BDmonth" maxlength="2" style="width:5%" />&nbsp/&nbsp
        <input class="text" id="BDday" maxlength="2" style="width:5%" />
        <br />
        <p id="bderror" style="position:absolute; top:70%; color:red; font:65% arial; display:none">תאריך לידה לא תקין</p>
        <p id="bderroryoung" style="position:absolute; top:70%; color:red; font:65% arial; display:none">חובה להיות מעל גיל 13</p>
    </td>
</tr>

脚本部分运行,无论我在输入中输入的是数字还是单词,都有任何长度,我不明白它为什么运行,但我怀疑是"isNaN"函数在不同的尝试和设置中无法正常工作。它应该找出输入的内容是否只是一个长度适合dd/mm/yyyy的numric值,如果它都是false,它应该保持一切原样,BDcheck var为true,这样下一个if语句将运行

有什么建议吗?

确保BDyear、BDday和BDmonth实际包含值;您可能需要在isNaN函数中使用document.getElementById("BDyear").value。该值也可能是一个字符串,因此在检查isNaN之前,您可能需要先尝试将其强制转换为数字,如下所示:isNaN(Number(document.getElementById("BDyear").value))

此外,isNaN返回一个布尔值,因此将其与true进行比较是多余的。你可以像if (isNaN(BDyear) || isNaN(BDmonth) || isNaN(BDday) || BDday.length != 2 || BDmonth.length != 2 || BDyear.length != 4)一样写,可能会有我刚才建议的修改。

最终,代码可能是这样的:

//assuming BDstate and BDcheck variables are already defined
var year = document.getElementById("BDyear");
var month = document.getElementById("BDmonth");
var day = document.getElementById("BDday");
if (isNaN(Number(year.value)) || isNaN(Number(month.value) || isNaN(Number(day.value)) || day.value.length != 2 || month.value.length != 2 || year.value.length != 4)
{
    year.value = ''
    month.value = ''
    day.value = ''
    document.getElementById("bderror").style.display = "inline"
    BDstate = false
    BDcheck = false
}

此外,您可能需要检查数值是否在有效范围内,而不是检查月份的字符串长度是否为2个字符。例如,用户当前必须输入"06"(不带前导或尾随空格,btw)才能成功进行检查,而如果您实际检查数值是否在(Number(month.value) >= 1 && Number(month.value) <= 12)等有效范围内,则用户可以输入" 6 "。一天一年都是如此。