【问题标题】:How can I update input value without refreshing the page [closed]如何在不刷新页面的情况下更新输入值[关闭]
【发布时间】:2021-03-10 11:37:24
【问题描述】:

好的,所以我正在尝试创建一个简单的小费计算器,但除非用户输入值然后刷新页面,否则它不起作用。我该如何解决这个问题,以便在输入数字时计算按下按钮而不刷新页面的时间。

document.addEventListener('DOMContentLoaded', function () {
document.getElementById('calculate').onclick = CalculatorForNumber
const billing = document.querySelector('#bill').value
const people = document.querySelector('#numberofpeople').value
const percent = document.querySelector('#percent').value
function CalculatorForNumber() {
    if (document.getElementById('type').value === document.getElementById('bynumberofpeople')){
        alert((billing/100)*people)
    } else{
        alert((billing/100)*percent)
    }

}

})

【问题讨论】:

标签: javascript html dom script


【解决方案1】:

您应该将 3 个变量 billingpeoplepercent 放入函数 CalculatorForNumber。

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('calculate').onclick = CalculatorForNumber

  function CalculatorForNumber() {
    const billing = document.querySelector('#bill').value
    const people = document.querySelector('#numberofpeople').value
    const percent = document.querySelector('#percent').value

    if (document.getElementById('type').value === document.getElementById('bynumberofpeople')){
        alert((billing/100)*people)
    } else{
        alert((billing/100)*percent)
    }
  }
})

这样做,每次点击计算按钮时,都会检索新数据进行计算

【讨论】:

  • 这段代码永远不会工作,你用字符串值进行计算
  • 我假设输入值已经过验证并且是数字
  • 这不适合宝贵的建议...
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 2013-10-04
  • 2017-03-24
  • 2022-11-27
  • 1970-01-01
相关资源
最近更新 更多