javascript - updating span是可以的,update input results in 'NaN'

标签 javascript jquery nan

我正在使用 jquery 和从 Yahoo! 获取最新汇率的 php 脚本转换价格

我的更新函数正在处理我可以使用 .text() 更新的元素(例如 span 元素),但是一旦我尝试设置输入元素的 .val(),它就会简单地接收到“NaN”——甚至虽然我对两者使用相同的值。

function frmtCurrency(ele,price) {
    // round the currency to the nearest .05
    price *= 2.0;
    price = price.toFixed(1) / 2.0;
    price = price.toFixed(2);

    //alert (parseInt(price)) here returns the amount, so it IS a number

    // check what type of element 'ele' is
    var element = (ele.get(0).tagName);

    if (element != 'INPUT') {
        ele.text(price+code); ALWAYS OK eg 10.55
    } else {
        ele.val(price); // ALWAYS NaN
    }
};

谁能告诉我为什么我不能更新输入字段但我可以更新跨度元素

最佳答案

function frmtCurrency(ele,price) {
    // round the currency to the nearest .05
    price = parseFloat(price);
    if(isNaN(price)) { price = 0 }
    price *= 2.0;
    price = price.toFixed(1) / 2.0;
    price = price.toFixed(2);
    ele.val(price);
}

frmtCurrency($('input'), '');

很可能是您在软件中的某个时刻传递了一个字符串或某些错误,结果为 NaN。在这里您可以看到我传递了一个空字符串,并添加了一个句柄以使其在未提供实数时显示为 0.00。

http://jsfiddle.net/kuroir/DaHSA/1/

关于javascript - updating span是可以的,update input results in 'NaN',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837691/

相关文章:

javascript - 将列表显示为环形缓冲区

jquery - 图像弹出不显示

python - 使用缺失值计算 scipy 中的成对距离

python - 为数组中的 nan 和 inf 值创建掩码

javascript - 未捕获的语法错误 : Cannot use import statement outside a module (Using Firebase)

javascript - 尝试使用 div 的类获取其 id

javascript - 仅订阅新条目或已删除条目的可观察数组

jquery - 悬停的 CSS 仅适用于 jQuery 的奇数行

javascript - 如何在整个 div 上应用链接?

Python:Pandas 在将字典传递给 resample() 后显示 NaN