公平警告,我是JS初学者:
尝试进行初学者项目(技巧计算器)。我一直在努力使这项工作太久了。
我试图获取输入/选择的值,做一个方程式,并将结果显示在底部。
但是该函数立即显示,而不是在单击按钮时显示。。。它显示的是NaN而不是我想要的值。我想念什么?
const billInput = document.getElementById('billInput');
const serviceInput = document.getElementById('serviceInput');
const peopleInput = document.getElementById('peopleInput');
const tipBtn = document.getElementById('tipBtn');
const tipOutput = document.getElementById('tipOutput');
tipBtn.addEventListener('click', tipCalculation());
function tipCalculation() {
let cost = Number(billInput.value);
let service = Number(serviceInput.value);
let people = Number(peopleInput.value);
document.getElementById('tipOutput').innerHTML = cost * service / people;
}
<div class="main-box">
<h2 class="title-top">What Should I Tip?</h2>
<div class="input-group">
<div class="pre">$</div>
<input type="number" id="billInput" placeholder="How much was the bill?">
</div>
<p class="titles service-title"></p>
<select required name="Service-lvl" id="serviceInput">
<option disabled selected>How was the service?</option>
<option value=".35">Amazing!</option>
<option value=".25">Solid</option>
<option value=".15">Meh...</option>
</select>
<div class="input-group bottom-input">
<input type="number" id="peopleInput" placeholder="How many are you splitting with?">
</div>
<button class="tipBtn" id="tipBtn">How Much Are You Tipping?</button>
<h3 id="tipOutput">Tip Ammount</h3>
</div>