我正在使用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