javascript"小于"if语句失败

ful*_*ons 3 javascript if-statement

这是我的功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

它检查Q,如果它小于0,则使其为0.然后,如果它不是0,但它小于E,则使其成为E.由于某种原因,此功能起作用,除非Q是一个两位数字.

例如,如果Q为7且E为2,则它将Q保留为7.但是,如果Q为10且E为2,则由于某种原因它认为10 <2,并且它将Q更改为2!

我在这里遗漏了什么?

Snu*_*gus 9

拉动.value元素时,它返回一个字符串.'10'<'2'将返回真实.

你可以简单地对值ala做一个parseInt/parseFloat

var q = parseInt(document.getElementById("Q"+i).value,10)
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用基数`parseInt(x,10)` (4认同)