[英]Why am I getting an NaN value?
我的jQuery是:
$("#listDB").on("change", ".qfStyle", function(event) {
var id = $(this).parents("tr").find('.itemCbox').val();
$qnty = $("#qnty"+id);
$unit = $("#unit"+id);
$price = $("#price"+id);
if($(this).parents("tr").find('.pbo').text()=="Kilos")
{
if(this.value<1)
{
$qnty.text(this.value*1000);
$unit.text("gm");
var data = "action=getPrice&id="+id;
$.post("addBill.php", data, function(json) {
alert(json.price);
$price.text(json.price*this.value);
}, 'json');
}
}
});
服务器返回的JSON数据是:
{ “价格”: “52.00”}
这里, this
是指文本框。 我得到了表达式的NaN
值:
$price.text(json.price*this.value);
但我确保this.value
和json.price
都是数字。 那么,为什么当我乘以NaN时会得到NaN?
问题是this
不在post
函数的范围内。
检查下面的代码。 我添加了一个新的变量value
,它保存this.value
的值,即使在post
函数中也应该可用。
$("#listDB").on("change", ".qfStyle", function(event) {
var id = $(this).parents("tr").find('.itemCbox').val();
$qnty = $("#qnty"+id);
$unit = $("#unit"+id);
$price = $("#price"+id);
var value = this.value;
if($(this).parents("tr").find('.pbo').text()=="Kilos")
{
if(value<1)
{
$qnty.text(value*1000);
$unit.text("gm");
var data = "action=getPrice&id="+id;
$.post("addBill.php", data, function(json) {
alert(json.price);
$price.text(json.price*value);
}, 'json');
}
}
});
您可以使用Number()将字符串编号提取为数字格式。
function getStringNumber(stringNumber){ var formatNumber = Number(stringNumber); console.log(formatNumber); }
<html> <button onclick="getStringNumber('24.00')"> Convert String Number </button> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.