非数字(NaN)-Javascript
我有一个函数,分别计算我的总数和费用。但当我发出警报时,我得到了NaN。为什么会这样非数字(NaN)-Javascript,javascript,jquery,Javascript,Jquery,我有一个函数,分别计算我的总数和费用。但当我发出警报时,我得到了NaN。为什么会这样 <script> sum = 0; charge = 0; $('.panel').append( '<div class="container" style=" font-size:14px; "> '+ '<table style="width:100%;" class="table" id="tabl
<script>
sum = 0;
charge = 0;
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<table style="width:100%;" class="table" id="tables">'+
'<td class="name" >'+std.name+'</td>'+
'<td><p class="total" ><span class="min-total" name="total" id="total"></span></p></td>'+
'</table>'+
'</div>'
$('.panel').on('keyup','.quantity',function()
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".min-total span").text(quantity * price);
sum = 0;
$(".sum-total").each(function(){
sum = sum + Number($(this).text());
})
}
$('.charge').on('keyup','.charge',function(){
$('.charge span').text( Number($(this).val()));
charge = Number($(this).val());
alert(sum + charge);
</script>
总和=0;
电荷=0;
$('.panel')。追加(
' '+
''+
''+std.name+''+
“”+
''+
''
$('.panel').on('keyup','.quantity',function()
容器=$(this).closest('div');
数量=数量($(this).val());
价格=数字($(this).closest('div')。查找('.price')。数据('price'));
container.find(“.min总跨度”).text(数量*价格);
总和=0;
$(“.sum total”)。每个(函数(){
sum=sum+Number($(this).text());
})
}
$('.charge').on('keyup','.charge',函数(){
$('.charge span').text(数字($(this.val()));
费用=数字($(this).val());
警报(总和+费用);
维基百科的定义是:
在计算中,NaN不是数字,而是一种数字数据类型
表示未定义或不可表示的值的值
在您的代码中,$(this).text()
或$(this).val()
不能由Number()计算并返回NaN
。请确保这些值是数字或由数字组成的字符串。请添加完整的代码以重现您的问题可能Number()
没有将某些文本值转换为数字。但是,如果没有更全面的示例,我们不可能说出其中的位置。发生这种情况时,您可以在每个点添加测试以将值设置为零。其中一个或两个字段包含非数字的内容,并且不能通过数字
转换为数字。您可以修复在调用Number
之前替换除数字以外的所有内容。可能的原因可能是在字段中使用逗号。$(this).val()
意味着.charge
是某种形式的表单字段。但是,您有$('.charge span'))
表示该表单字段的后代有一个span
,这是不可能的,因为大多数表单字段都没有子内容。请尝试分别输出sum
和alert
的值,以确定哪一个不是数字。例如alert(sum);alert(charge)是的,但这并不能解释NaN的来源。没有更多的代码,没有人能提供准确的答案。问题是“为什么会发生这种情况?”而且,由于我们没有足够的信息,无法确定。我们可以解释它是如何发生的(文档也可以),但我们无法解释为什么会在这里发生。