将值设置为输入类型编号无法正常工作

时间:2018-04-18 10:18:53

标签: javascript jquery html5

我想使用Jquery设置一个输入类型number的值。当值的长度超过15个字符时,它不起作用。

以下是我的示例代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#user").val(11111111111111444444444888888888);
    });
});
</script>
</head>
<body>
<p>Name: <input type="number" id="user" ></p>
<button>Set the value of the input field</button>
</body>
</html>

结果是:

  

11111111111111400000000000000000

对我来说意外。为什么它在15个字符后变为零?当数字的长度小于15时,它工作正常。我尝试使用minmax属性,但这也不起作用。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我认为这是因为javascript数字总是64位浮点数。

与许多其他编程语言不同,JavaScript没有定义不同类型的数字,如整数,短整数,长整数,浮点数等。

JavaScript编号始终存储为双精度浮点数,符合国际IEEE 754标准。

示例:

TopShelf

W3Schools收集的解释和示例。

也许您可以将var x = 999999999999999; // x will be 999999999999999 var y = 9999999999999999; // y will be 10000000000000000 添加到'',以便将值作为字符串传递。

答案 1 :(得分:0)

由于Goediaz对此行为有解释, 您可能希望将其作为字符串放在val()中。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#user").val(11111111111111444444444888888888);
        console.log("Number:", $("#user").val());
        $("#user").val("11111111111111444444444888888888");
        console.log("String:", $("#user").val());
    });
});
</script>
</head>
<body>
<p>Name: <input type="number" id="user" ></p>
<button>Set the value of the input field</button>
</body>
</html>

相关问题