【问题标题】:parseFloat() Not WorkingparseFloat() 不工作
【发布时间】:2014-10-17 15:37:29
【问题描述】:

我想知道我做错了什么?我正在尝试将一些数字放入 javascript vars 并添加它们,但是当我取消注释打印值的行时,它们都是 NaN。

<div id="priceDisplayPoolHeating">8.00</div>
<div id="priceDisplayPetFee">7.00</div>
<div id="priceDisplayPropertyDamageProtection">4.00</div>
<div id="priceDisplayVacationPackageTotal">9.80</div>
function recalculateGrandTotal() {
  var alreadySetCosts = 30.00;

  var thePoolHeatingFeeRounded = parseFloat(document.getElementById("priceDisplayPoolHeating").value);
  var thePetFeeRounded = parseFloat(document.getElementById("priceDisplayPetFee").value);
  var thePropertyDamageProtectionFeeRounded = parseFloat(document.getElementById("priceDisplayPropertyDamageProtection").value);

  var theGrandTotal = alreadySetCosts + thePoolHeatingFeeRounded + thePetFeeRounded + thePropertyDamageProtectionFeeRounded;

  document.getElementById("priceDisplayVacationPackageTotal").innerHTML = theGrandTotal;
  document.write('<br/>The Vars: ' + alreadySetCosts + '<br/>' + thePoolHeatingFeeRounded + '<br/>' + thePetFeeRounded + '<br/>' + thePropertyDamageProtectionFeeRounded + '<br/>' + theGrandTotal);
}

【问题讨论】:

  • 请发布一个完整的代码示例。
  • 没有看到HTML,很难说。
  • 只是一个旁注,我建议不要在变量名前加上the。写grandTotal 比写theGrandTotal 更简洁。
  • 问题是"bla bla bla... dummy text"。我认为这需要在&lt;script&gt; 标签内而不是在它之后
  • 在没有完全意识到这一点的情况下,我想到了更多独特的变量名称,以防止与更大的脚本/应用程序中的移植或本机代码混淆或冲突。

标签: javascript getelementbyid parsefloat


【解决方案1】:

这是因为 div 标签没有value

<div id="priceDisplayPoolHeating" class="priceDisplay">8.00</div>

你必须用这样的代码改变你的 JS 行:

document.getElementById("priceDisplayPoolHeating").value

改为获取文本:

document.getElementById("priceDisplayPoolHeating").innerHTML

在调试时,您应该尝试查看 document.getElementById("priceDisplayPoolHeating").value 等值中包含的内容。如果你这样做了,你会看到它返回undefinedparseFloat(undefined); 返回NaN

【讨论】:

    【解决方案2】:

    您正在尝试访问元素的值属性...

    document.getElementById("priceDisplayPropertyDamageProtection").value
    

    你需要文本内容:

    document.getElementById("priceDisplayPropertyDamageProtection").textContent
    

    希望对你有帮助?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      相关资源
      最近更新 更多