javascript“小于"如果语句失败 [英] javascript "less than" if statement failing

查看:76
本文介绍了javascript“小于"如果语句失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的功能:

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 <2,并将Q更改为2. !

我在这里想念东西吗?

解决方案

当您拉出元素的.value时,它将返回一个字符串. '10'<'2'将返回true.

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

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

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.

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!

Am I missing something here??

解决方案

When you pull the .value of an element it returns a string. '10'<'2' will return true.

You can simply do a parseInt/parseFloat on the value, ala

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

这篇关于javascript“小于"如果语句失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆