1

我有一个函数可以显示各种下拉列表的数字总数。如果下拉列表之一设置为 #(起始值),则结果值显示为 NaN。

我想更改 NaN 在我的页面上的显示方式。我希望它读为“--”而不是“NaN”。

这是带有变量和 if/else 省略的函数:

function multiply() {
    $('#total').text((((beds * perhour) + (addbath)) * discount ));
}

如何将文本设置为--而不是NaN

4

4 回答 4

3

一个简单的解决方法是利用 NaN 是一个虚假值这一事实

function multiply() {
    $('#total').text(((((beds * perhour) + (addbath)) * discount)) || 0);//instead of 0 you can pass any default value here like an empty string
}
于 2013-08-29T03:01:56.563 回答
2

你可以使用isNaN()来比较你得到的是数字还是 NaN,你可以使用三元条件运算符来获取分配result或字符串常量"--"到 div。

result = isNaN((((beds * perhour) + (addbath)) * discount ))
$('#total').text(isNaN((result) ? "--" : result) 
于 2013-08-29T03:02:05.760 回答
0
function multiply() {
    var total = ((beds * perhour) + (addbath)) * discount; 
    $('#total').text(!isNan(total) ? total : '--');
}
于 2013-08-29T03:07:06.727 回答
0

您可以在 jquery 中使用 isNumeric 函数,

 $.isNumeric(NaN);    // false

参考这个,http://api.jquery.com/jQuery.isNumeric/

于 2013-08-29T04:07:56.093 回答