[英]How do i make this HTML styled calculator work only using JS
我已經被這個任務困了很長時間了。
基本上我有這個重寫的 HTML 代碼
<input type="text" id="num1" value="" placeholder="input whole number" />
<input type="text" id="num2" value="" placeholder="input whole number" />
<br> <br>
Click on a operator:
<br>
<input type="button" id="add" class="operator" value="+" />
<input type="button" id="subtract" class="operator" value="-" />
<input type="button" id="multiply" class="operator" value="*" />
<input type="button" id="divide" class="operator" value="/" />
<p class="semig">Result is: <span id="resultat">???</span></p>
我只允許使用 JS 使計算器工作,而不能編輯 HTML。
通常我會在 JS 中編寫 function 但在 HTML 代碼中調用 function。
誰能幫我這個?
考慮一個通用事件處理程序:
function buttonClick(event) {
alert("You clicked " + event.target.id);
}
這些按鈕具有 ID,因此您可以將事件偵聽器附加到它們。
document.getElementById("add").addEventListener("click", buttonClick, false);
// etc... for the other buttons
更好的是,它們有類,因此您可以查找它們並附加事件偵聽器:
Array.from(document.querySelectorAll("button.operator")).forEach(btn => {
btn.addEventListener("click", buttonClick, false);
});
一個更高級的選項是在例如document.body
上添加點擊處理程序並使用事件傳播/冒泡來查看實際點擊的元素。
您可以嘗試使用此代碼:
var addButton = document.getElementById("add"); addButton.onclick = function() { calculate("+"); } var subtractButton = document.getElementById("subtract"); subtractButton.onclick = function() { calculate("-"); } var multiplyButton = document.getElementById("multiply"); multiplyButton.onclick = function() { calculate("*"); } var divideButton = document.getElementById("divide"); divideButton.onclick = function() { calculate("/"); } function calculate(operation) { var num1 = document.getElementById("num1").value; var num2 = document.getElementById("num2").value; try { eval("var result = " + num1.toString() + operation + num2.toString()); document.getElementById("resultat").innerHTML = result; } catch { alert("You must enter numbers in theses fills"); } }
<html> <body> <input type="text" id="num1" value="" placeholder="input whole number" /> <input type="text" id="num2" value="" placeholder="input whole number" /> <br> <br> Click on a operator: <br> <input type="button" id="add" class="operator" value="+" /> <input type="button" id="subtract" class="operator" value="-" /> <input type="button" id="multiply" class="operator" value="*" /> <input type="button" id="divide" class="operator" value="/" /> <p class="semig">Result is: <span id="resultat">???</span></p> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.