2016-03-26 15 views
0

は私が0にデフォルトで設定されたテーブルのヘッド<th>を持っています。したがって、新しい値が20000の場合、値は20000+0=20000でなく、200000でなければなりません。そして、別の商品を追加した場合、価格は30,000で、20000030 000のようになります。jQueryの不要な加算結果

これは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

+0

あなたは 'のparseInt()を'使用する必要があります。 '+'演算子は、文字列の追加や連結に使用されます。また、DOM要素のテキストを読むと、数字ではなく文字列として読み取られます。 – Rajesh

+1

正しい解決策がありましたが、 '+'を 'initial'の後ろに置くことを忘れました。 '+ initial + +(res ['price']);' –

+0

小数点が必要な場合は、代わりにparseFloatを実行してください。また、 "30 000"や "30,000"のようなものを30000として認識させるには、最初にそれらを取り除かなければなりません。 'res ['price']のようなことをしてください。replace(/ [、]/g、 '') – David784

答えて

4

あなたは整数にテキスト(文字列)を解析し、それを追加する必要があります。あなたはDOM要素からテキストを読んだとき、私はすでに、コメントしているように、あなたの計算のために、以下の

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

を得ることができ、それを文字列として読み込まれ、 +オペレータを適用すると、そのコンカチネーションと追加として扱われます。続き

は、シミュレーションです:

(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); 
 
})()
<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>

はまた、ポスト、以下ご参照ください:parseInt vs unary plus

関連する問題