【问题标题】:javascript "less than" if statement failingjavascript“小于”if语句失败
【发布时间】:2012-12-27 23:29:24
【问题描述】:

这是我的功能:

function reCalculate(i) {
    document.getElementById("Q" + i).value = document.getElementById("C" + i).value - document.getElementById("QA" + i).value;

    if (document.getElementById("Q" + i).value < 0) {
        document.getElementById("Q" + i).value = 0;
    }
    if (document.getElementById("Q" + i).value < document.getElementById("E" + i).value && document.getElementById("Q" + i).value != 0) {
        alert(document.getElementById("Q" + i).value + " is less than " + document.getElementById("E" + i).value + "?");
        document.getElementById("Q" + i).value = document.getElementById("E" + i).value;
    }
    document.getElementById("Q" + i).value = Math.ceil(document.getElementById("Q" + i).value);
}

它检查 Q,如果小于 0,则为 0。然后,如果不是 0,但小于 E,则为 E。出于某种原因,此函数有效,除非 Q 是两位数。

例如,如果 Q 为 7,E 为 2,那么它将 Q 保留为 7。但是,如果 Q 为 10,E 为 2,由于某种原因,它认为 10

我在这里错过了什么吗??

【问题讨论】:

  • 请将您的 DOM 元素缓存到变量中。每次使用 getById 都会回到 DOM 中,并且性能代价高昂。
  • 好点,我修好了,谢谢!

标签: javascript if-statement


【解决方案1】:

当您拉取元素的.value 时,它会返回一个字符串。 '10'&lt;'2' 将返回 true。

您可以简单地对值执行 parseInt/parseFloat,ala

var q = parseInt(document.getElementById("Q"+i).value,10)

【讨论】:

  • 你应该使用基数parseInt(x,10)
【解决方案2】:

那是因为它在比较时将您的 Q 视为 字符串。

请尝试以下方法:

function reCalculate(i){

    var Z = document.getElementById, P = parseInt; 

    var qElem = Z("Q"+i);
    var q = P(qElem.value, 10);
    var c = P(Z("C"+i).value, 10);
    var qa = P(Z("QA"+i).value, 10);
    var e = P(Z("E"+i).value, 10);

    q = c - qa;

    if (q < 0) qElem.value = 0;

    if (q < e && q != 0){
        alert(q+" is less than "+e+"?");
        qElem.value = e;
    }

    qElem.value = Math.ceil(q);
}

【讨论】:

  • 告诉发帖者如何修复它!
  • @epascarello - 在发布之前正在格式化代码.. :-)
  • 一个很好的旁注:除了更短的代码,使用var Z = document.getElementById; 实际上使代码更高效。 Same principle as this here.
【解决方案3】:

也许你应该做一个

parseFloat(document.getElementById("Q"+i).value)

确保您在比较数字

【讨论】:

    【解决方案4】:

    您是在比较 字符串 而不是数字。使用一元 + 转换为数字:

    if (+document.getElementById("Q" + i).value < +document.getElementById("E" + i).value ...)
    

    你应该顺便使用变量:

    var input_one = document.getElementById("Q" + i).value,
        input_two = document.getElementById("E" + i).value;
    
    if (+input_one < +input_two) {
    
    }
    

    【讨论】:

    • 作为记录,它没有按长度进行比较。不过,我不太确定比较的是什么。 ('10' 比 '2' 长,但是 '10' &lt; '2' 的计算结果为 true)
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 2019-01-26
    • 2021-10-17
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多