首页 > 解决方案 > 输入类型编号加 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每次都发生。

你们知道为什么会这样吗?

标签: javascriptjqueryhtml

解决方案


如您所说,使用 parseInt() 否则输入值将被视为字符串。

    $('#a').bind('input propertychange', function() {
      number_a = parseInt($(this).val());
// call the calculation function
        calculate();
       });

推荐阅读