parseFloat() Not Working

parseFloat() Not Working

本文关键字:Working Not parseFloat      更新时间:2023-09-26

我想知道我做错了什么?我试图将一些数字放入javascript变量中并添加它们,但当我取消注释打印值的行时,它们都是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);
}
这是因为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

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

document.getElementById("priceDisplayPropertyDamageProtection").value

您需要文本内容:

document.getElementById("priceDisplayPropertyDamageProtection").textContent

我希望这有帮助?