Basic Tip Calculator JavaScript

问题描述 投票:-2回答:2

我非常基本的小费计算器无法正常工作。我觉得我的逻辑是正确的,语法应该没问题,但是我遗漏了一些东西,因此我已经花了太多时间。请帮忙。非常感谢。

<body>
<input type='number' placeholder='Total price' id='user-input'/>
<button id="calculator">Calculate the tip</button>
<h3 id='result'></h3>
<script>
  var userInput = document.getElementById('user-input');
  var button = document.getElementById('calculator');
  var h3El = document.getElementById('result');
  button.addEventListener('click', tipCalculator);
  function tipCalculator(){
    var tip = userInput * 0.1;
    h3El.innerHTML = tip;
  }
  tipCalculator();
</script>
javascript addeventlistener innerhtml getelementbyid
2个回答
0
投票

由于值为字符串,所以显示NaN

var userInput = document.getElementById('user-input').value;
userInput = parseInt(userInput) //convert it into Number

0
投票

更改此

var userInput = document.getElementById('user-input');

对此

var userInput = document.getElementById('user-input').value;
© www.soinside.com 2019 - 2024. All rights reserved.