简体   繁体   English

jQuery-如何将NaN更改为其他内容

[英]JQuery - How to change a NaN to something else

I have a function that displays a numerical total of various dropdowns. 我有一个函数,可以显示各种下拉菜单的数字总计。 If one of the dropdowns is set to # (the starting value), the resulting value is displayed as NaN. 如果下拉菜单之一设置为#(起始值),则结果值将显示为NaN。

I want to change how NaN is displayed on my page. 我想更改NaN在页面上的显示方式。 I want it to read "--" instead of "NaN". 我希望它显示为“-”而不是“ NaN”。

Here is the function with variables and if/elses omitted: 这是带有变量和if / elses省略的函数:

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

How can I set the text to -- instead of NaN ? 如何将文本设置为--而不是NaN

An easy fix is to use the fact that NaN is a falsy value 一个简单的解决方法是使用NaN是虚假的值的事实

function multiply() {
    $('#total').text(((((beds * perhour) + (addbath)) * discount)) || 0);//instead of 0 you can pass any default value here like an empty string
}

You can use isNaN() to compare if you got number or NaN, you can use ternary conditional operator to get assign result or string constant "--" to div. 您可以使用isNaN()比较是否有数字或NaN,可以使用三元条件运算符获取分配result或将字符串常量"--"分配给div。

result = isNaN((((beds * perhour) + (addbath)) * discount ))
$('#total').text(isNaN((result) ? "--" : result) 
function multiply() {
    var total = ((beds * perhour) + (addbath)) * discount; 
    $('#total').text(!isNan(total) ? total : '--');
}

You can use isNumeric function in jquery, 您可以在jquery中使用isNumeric函数,

 $.isNumeric(NaN);    // false

Refer this, http://api.jquery.com/jQuery.isNumeric/ 请参阅http://api.jquery.com/jQuery.isNumeric/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM