我刚刚开始学习 JavaScript。我将要学习 DOM 操作,对很多 JavaScript 知识还很陌生...从我的代码中你可能就能看出来!
我正在尝试制作小费计算器(我想这是新手常做的项目),但是在 DOM 方面和如何选择某些输入元素(文本和单选按钮)以及提交它们方面遇到了困难。
请帮我修改下面的代码,提供任何建议都非常感谢。我愿意接受教训并改掉所有错误,非常渴望学习正确操作!
<form class="container">
<h2>Tip Calculator</h2>
<p>Enter Bill Amount</p>
<input type="text" class="input-styles" placeholder="£££" id="bill-amount">
<p>Select Percentage Of Bill</p>
<div class="radio-container">
<div class="radio-styles"> <p>10%</p>
<input type="radio" class="radio-styles" name="tip-percent" value="0.1">
</div>
<div class="radio-styles">
<p>15%</p>
<input type="radio" class="radio-styles" name="tip-percent" value="0.15">
</div>
<div class="radio-styles">
<p>20%</p>
<input type="radio" class="radio-styles" name="tip-percent" value="0.2">
</div>
<div class="radio-styles">
<p>25%</p>
<input type="radio" class="radio-styles" name="tip-percent" value="0.25">
</div>
</div>
<div class="submit-container">
<button type="submit" name="tip-submit" id="submit-button">submit</button>
</div>
<div class="totals-container">
<div class="totals">
<h2>Tip To Pay</h2>
<h2 id="tip-to-pay"></h2>
<h2 id="bill-final">Total Bill To Pay</h2>
<h2 id="bill-to-pay"></h2>
</div>
</div>
</form>
以下是Javascript代码...
var bill, percent, tip, finalBill;
document.getElementById('submit-button').addEventListener('click', function() {
// get bill amount
bill = document.getElementById('bill-amount').value
//get percent amount from checkboxes
percent = document.getElementsByName('tip-percent').checked;
tip = calcTip();
finalBill = finalAmount();
// edit results in html
document.getElementById('tip-to-pay').textContent = tip;
document.getElementById('bill-to-pay').textContent = finalBill;
// display result
document.querySelector('.totals-container').style.display = 'flex';
}
function calcTip() {
tip = percent * bill
}
function finalAmount() {
finalBill = tip + bill
}
如果您查看下面的画笔,可能会更容易理解这个问题! https://codepen.io/rickwall/pen/WNbpmoW