【问题标题】:jQuery parseFloat not working as expectedjQuery parseFloat 没有按预期工作
【发布时间】:2016-02-17 01:26:31
【问题描述】:

全部。我正在尝试将字符串更改为浮点数,以便可以将其格式化为货币。问题是,parseFloat 不断返回 NaN。我错过了什么?这是JSFiddle

HTML:

<div class="value num">948572</div>
<div class="value num">34567</div>
<div class="value num"></div>

JS:

jQuery(document).ready(function($) {
  $('.value.num').each(function() {
    if( $(this).is(':empty')) {
      $(this).text('$0.00');
    } else {
      var numValue = Number.parseFloat($(this), 10);
      $(this).text('$' + (numValue / 100).toFixed(2));
    }
  });
});

【问题讨论】:

    标签: javascript jquery html parsefloat


    【解决方案1】:

    如果您想使用 jQuery 获取 html 元素的文本,请使用 .text()

    jQuery(document).ready(function($) {
      $('.value.num').each(function() {
        if( $(this).is(':empty')) {
          $(this).text('$0.00');
        } else {
          var numValue = Number.parseFloat($(this).text(), 10);
          $(this).text('$' + (numValue / 100).toFixed(2));
        }
      });
    });
    

    【讨论】:

      【解决方案2】:

      $(this) 指的是.value.num 元素。将其更改为:

      var numValue = Number.parseFloat($(this).text());
      

      (另外,parseFloat 没有第二个参数)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-17
        • 2019-07-13
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多