为什么这个连接而不是加起来

zik*_*zik 1 html javascript jquery

非常非常基本的问题,但我有以下HTML:

<input type="text" id="nspcc" value="0" onkeyup="doTotal();" />
<input type="text" id="barnados" value="0" onkeyup="doTotal();" />
<input type="text" id="savethechildren" value="0" onkeyup="doTotal();" />
<input type="text" id="childresnsociety" value="0" onkeyup="doTotal();" />
<input type="text" id="childreninneed" value="0" onkeyup="doTotal();" />
<input type="text" id="total" disabled="disabled"  />
Run Code Online (Sandbox Code Playgroud)

以下是jQuery:

function doTotal() {
  var one,two,three,four,five,total;
  one = $('#nspcc').val();
  two = $('#barnados').val();
  three = $('#savethechildren').val();
  four = $('#childresnsociety').val();
  five = $('#childreninneed').val();
  total = one+two+three+four+five;
  $('#total').val(total);
}

doTotal();
Run Code Online (Sandbox Code Playgroud)

我可能正在做一些愚蠢但为什么total连接而不是添加值?我需要使用parseInt什么?

Jam*_*ice 6

我需要使用parseInt吗?

是.该.val()方法返回一个字符串,因此您需要确保对数字进行+操作(因为运算符被重载以根据上下文执行加法和连接):

one = parseInt($('#nspcc').val(), 10);
//etc...
Run Code Online (Sandbox Code Playgroud)

不要忘记第二个参数(基数)parseInt!