javascript 表示 4 大于 16

javascript says that 4 is higher than 16

function getNum() {
    num = $('.slicesinput').val();
    num2 = $('.numinput').val();
    if (num === "" || num2 === "") {
        alert('Your inputs may not be empty, else the diagram won\'t work proper...');
    } else {
        if (num > num2) {
            alert('Whoops, ' + num + ' is a higher number than ' + num2 + ', please fix this and try again');
        } else if (num === num2) {
            alert('Woops, ' + num + ' and ' + num2 + ' is the same number...');
        } else {
            progressBarUpdate(num, num2);
        }
    }
}

HTML

<p>Number of slices you want</p>
<input name="slices" class="slicesinput" type="text"/>
<p>Out of max slices</p>
<input name="num" class="numinput" type="text"/>
<p>Ex. 3 + 6</p>
<input type="submit" onclick="getNum()"/>

当我在第一个 ex 4 和第二个 16 提交时,它会弹出一个警告 "Woops, 4 is a higher number than 16, please fix this and try again",但如果我选择 4 和 6,它工作正常..?实际问题是什么?我该如何解决这个问题?

尝试将您的 'num' 变量放入 Number() 函数中,因为它们可能会作为字符串而不是数字进行比较。您还可以将输入的类型更改为数字。

当你得到文本框的值时,

num = $('.slicesinput').val();

您得到的是一个字符串值,而不是一个数字。所以你比较的实际上是 2 个字符串而不是数字。您需要将字符串解析为数字才能使其正常工作

num = Number($('.slicesinput').val());