简体   繁体   English

javascript“小于”if语句失败

[英]javascript “less than” if statement failing

Here is my function: 这是我的功能:

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);
}

It checks Q, if it's less than 0, it makes it 0. Then, if it's not 0, but it's less than E, it makes it E. For some reason this function works UNLESS Q is a double digit number. 它检查Q,如果它小于0,则使其为0.然后,如果它不是0,但它小于E,则使其成为E.由于某种原因,此功能起作用,除非Q是一个两位数字。

For example, if Q is 7 and E is 2, then it will leave Q at 7. However, if Q is 10 and E is 2, for some reason it thinks that 10<2, and it changes Q to 2! 例如,如果Q为7且E为2,则它将Q保留为7.但是,如果Q为10且E为2,则由于某种原因它认为10 <2,并且它将Q更改为2!

Am I missing something here?? 我在这里遗漏了什么?

When you pull the .value of an element it returns a string. 拉动元素的.value ,它返回一个字符串。 '10'<'2' will return true. '10'<'2'将返回true。

You can simply do a parseInt/parseFloat on the value, ala 你可以简单地对值ala做一个parseInt / parseFloat

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

Thats because it is considering your Q as a string while comparing. 那是因为它在比较时考虑你的Q作为字符串

Try the following instead: 请尝试以下方法:

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);
}

May be you should do a 也许你应该做一个

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

to make sure you are comparing numbers 确保你比较数字

You are comparing strings not numbers. 您正在比较字符串而不是数字。 Use the unary + to convert to a number: 使用一元+转换为数字:

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

You should use variables by the way: 您应该使用变量:

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

if (+input_one < +input_two) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM