我正在使用Jquery.Ajax並希望使用ajax響應和預定義變量做一些補充。我的代碼如下 -JQuery簡單加法問題
success: function(response)
{
$('#net_amount').html("$"+(credit+response));
}
假設「響應」 10和「信用」 20,它打印2010我希望它是30(20 + 30)。
我該怎麼辦?
我正在使用Jquery.Ajax並希望使用ajax響應和預定義變量做一些補充。我的代碼如下 -JQuery簡單加法問題
success: function(response)
{
$('#net_amount').html("$"+(credit+response));
}
假設「響應」 10和「信用」 20,它打印2010我希望它是30(20 + 30)。
我該怎麼辦?
因爲+
用於javascript中的連接以及加法,所以您需要確保變量的類型是數字,而不是字符串。
您的選擇是使用parseInt()
和parseFloat()
。我會建議後者,因爲你正在處理貨幣價值的例子。
success: function(response) {
$('#net_amount').html("$" + (parseFloat(credit) + parseFloat(response)));
}
所有你需要做的是首先將值解析爲一個整數,如下所示:
$('#net_amount').html("$" + (parseInt(credit) + parseInt(response)));
響應或信用卡被視爲字符串。 (可能是迴應)。
success: function(response)
{
$('#net_amount').html("$"+(parseInt(credit)+parseInt(response)));
}
以上將得到預期的結果
use parseInt() or parseFloat() its convert into Integer format
E;g:
var credit = '30';
response= '20';
alert(typeof(response)); // string
alert("++++++++++++"+"$"+(parseInt(credit)+parseInt(response))+"++++++++++++");
if your value as in Integer, then u no need to go for parseInt(),parseFloat()
var credit = 30;
response= 20;
alert(typeof(response)); // // Integer
alert("++++++++++++"+"$"+((credit)+(response))+"++++++++++++");
最少。可讀。回答。永遠。 – 2012-02-21 13:37:18
另一種解決方案是在1要添加他們同時乘以信貸和響應的值。這將強制JS將它們視爲數值而不是字符串。
success: function(response)
{
$('#net_amount').html("$"+((credit*1.00)+(response*1.00)));
}
謝謝,工作。 – skos 2012-02-21 13:23:13
@confused_developer很高興爲您提供幫助。 – 2012-02-21 13:25:18
+1 for parseFloat() – 2012-02-21 13:27:46