javascript - 输入类型编号加 10 到值
问题描述
我刚刚在最简单的代码中发现了一个奇怪的行为,我想知道为什么会这样。
我有 3 inputs
(a, b, c) 类型number
,每当它们发生变化时,我都会用 jQuery 将值存储在一个全局变量中(每个输入一个变量)。然后我调用一个函数来计算 3 个变量的平均值(a + b) / c
。当我console.log
变量和总数时,它正在返回((a + 10) + b) /c
。不知何故,它只向第一个变量添加了 10,我不知道为什么。
number_a = 0;
number_b = 0;
number_c = 0;
$('#a').bind('input propertychange', function() {
number_a = $(this).val();
calculate();
});
$('#b').bind('input propertychange', function() {
number_b = $(this).val();
calculate();
});
$('#c').bind('input propertychange', function() {
number_c = $(this).val();
calculate();
});
function calculate() {
var total = 0;
if (number_c) {
total = (number_a + number_b) / number_c;
} else {
total = (number_a + number_b) / 1;
}
console.log(number_a, number_b, number_c);
console.log(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" placeholder="a" />
<input type="number" id="b" placeholder="b" />
<input type="number" id="c" placeholder="c" />
我知道我可以使用parseInt()
从输入中获得的值来解决这个问题,因为它们是字符串,但这很奇怪它只发生在a
输入中并且10
每次都发生。
你们知道为什么会这样吗?
解决方案
如您所说,使用 parseInt() 否则输入值将被视为字符串。
$('#a').bind('input propertychange', function() {
number_a = parseInt($(this).val());
// call the calculation function
calculate();
});
推荐阅读
- python - 如何有效地处理 parquet 文件的内容
- python - 为什么我的 Python 并行进程运行次数过多?
- selenium - Selenium 驱动程序无法下载 JAVA
- android - 华为推送和SDK统计问题
- java - 在使用 Jackson 序列化类时添加类型信息,以便可以在不使用注释的情况下使用接口类型进行反序列化?
- security - 确保路径不会脱离基本路径
- python - pandas DataFrame:列中相同符号的值相加的最大值和最小值
- powershell - 脚本仅适用于本地机器
- html - 边框的意外 CSS 行为
- javascript - 使用 D3.js 的不同条形数据 x 轴