jQuery parseFloat 没有按预期工作

jQuery parseFloat not working as expected

全部。我正在尝试将字符串更改为浮点数,以便将其格式化为货币。问题是,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('[=12=].00');
    } else {
      var numValue = Number.parseFloat($(this), 10);
      $(this).text('$' + (numValue / 100).toFixed(2));
    }
  });
});

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

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

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

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

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