【问题标题】:Trying to add two value and insert them in HTML as a paragraph尝试添加两个值并将它们作为段落插入 HTML
【发布时间】:2022-09-23 21:23:29
【问题描述】:

我目前正在尝试使此代码正常工作。

我认为问题出在我的代码的最后两行,但我不明白为什么它不起作用。我不能添加这两个值并将结果插入我的 HTML 吗?

const option1=document.getElementById(\"checkbox1\")
const option2=document.getElementById(\"checkbox2\")
const option3=document.getElementById(\"checkbox3\")
let priceFirstMonth = 19.95;
let priceAnnual = 29.95;
const setPriceMonth = document.querySelector(\".firstMonthPrice\");

const calculatedPrice = () => {
    /* calculate the amount of all options */
    let addedOptionsPrice;
    if (option1.checked) {
        addedOptionsPrice = addedOptionsPrice+10;
    }
    if (option2.checked) {
        addedOptionsPrice = addedOptionsPrice+5;
    } 
    if (option3.checked) {
        addedOptionsPrice = addedOptionsPrice+10;
    }

    /* add the amount to regular prices*/
    priceFirstMonth = document.createElement(\'p\');
    priceAnnual = document.createElement(\'p\');
    priceFirstMonth.innerHTML = priceFirstMonth + addedOptionsPrice;
    priceAnnual.innerHTML = priceAnnual + addedOptionsPrice;
    setPriceMonth.appendChild(priceFirstMonth);

}

提前感谢您对我的行为的任何帮助或解释!

    标签: javascript


    【解决方案1】:

    只需重命名变量。

    const priceFirstMonthElement = document.createElement('p');
    const priceAnnualElement = document.createElement('p');
    priceFirstMonthElement.innerHTML = priceFirstMonth + addedOptionsPrice;
    priceAnnualElement.innerHTML = priceAnnual + addedOptionsPrice;
    setPriceMonth.appendChild(priceFirstMonthElement);
    

    您只是将元素分配给用于计算的同一变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多