jQuery不需要的总和结果

时间:2016-03-26 14:56:04

标签: javascript jquery

我有一个表头<th>,默认设置为0

<th id="total_price" style="text-align:center">0</th>

现在,当我添加新的已售商品时,价格应添加到此<th>的值中。因此,如果新的值为20000,则值应为20000+0=20000而不是200000。如果我添加另一个项目,价格为30 000,现在就像20000030 000

这是jquery脚本:

        var initial = $("#total_price").text();
        console.log(initial);
        var newPrice = initial + (res['price']);
        console.log(newPrice);
        $("#total_price").text(newPrice);

我试过了:

        var initial = $("#total_price").text();
        console.log(initial);
        var newPrice = initial + +(res['price']);
        console.log(newPrice);
        $("#total_price").text(newPrice);

但仍然一样。

enter image description here

2 个答案:

答案 0 :(得分:4)

您需要将文本(字符串)解析为整数,然后将其添加。所以在下面进行计算

 var newPrice = parseInt(initial,10) + parseInt(res['price'],10);

或者what you are trying would be a string concatenation and not a Sum

您可以 More info Here

答案 1 :(得分:1)

正如我已经评论过的那样,当您从DOM元素中读取文本时,它将被读取为字符串,当您将+运算符应用于它时,它将被视为连接和添加。

以下是模拟:

&#13;
&#13;
(function(){
  var th = $("th");
  var result = "";
  
  result += "Direct addition: " + $(th[0]).text() + $(th[1]).text() + "<br/>";
  result += "Type: " + typeof($(th[0]).text()) + "<br/>";
  result += "Parse Int: " + (parseInt($(th[0]).text()) + parseInt($(th[1]).text())) + "<br/>";
  $("#result").html(result);
})()
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
  <tr>
    <th>20000</th>
    <th>0</th>
  </tr>
</table>
<p id="result"></p>
&#13;
&#13;
&#13;

另请参阅以下帖子:parseInt vs unary plus

相关问题