计算器功能优化需求:等号触发后首次数字键清空双输入框
Hey there! Let's fix up your calculator with the auto-clear functionality you need, plus some quality-of-life improvements. Here's how we'll do it:
Solution for Auto-Clear After Calculation + Optimizations
Modified Complete Code
This version implements the auto-clear on first number press after calculation, along with several other tweaks:
<html> <head> <meta charset="UTF-8" /> <title>Taschenrechner</title> <script type="text/javascript"> // Flag to track if we need to clear displays on next number input let shouldClear = false; function Check(input) { const allowedChars = "0123456789[]()-+*%/."; for (let i = 0; i < input.length; i++) { if (allowedChars.indexOf(input.charAt(i)) < 0) return false; } return true; } function Ergebnis() { const input = window.document.Rechner.Display.value; if (Check(input)) { window.document.Rechner.Display2.value = input; try { const result = eval(input); window.document.Rechner.Display.value = "=" + result; shouldClear = true; // Set flag for auto-clear on next number press } catch (error) { window.document.Rechner.Display.value = "Error"; shouldClear = true; } } else { window.document.Rechner.Display.value = "Invalid Input"; shouldClear = true; } } function add(char) { // Check if we need to clear displays (only for numbers/decimal) if (shouldClear && /[0-9.]/.test(char)) { window.document.Rechner.Display.value = ""; window.document.Rechner.Display2.value = ""; shouldClear = false; // Reset flag after clearing } window.document.Rechner.Display.value += char; } function backspace() { const currentValue = window.document.Rechner.Display.value; window.document.Rechner.Display.value = currentValue.slice(0, -1); } // Initialize history table once (instead of recreating every time) const historyDiv = document.getElementById("Historie"); const historyTable = document.createElement("TABLE"); const historyTableBody = document.createElement("TBODY"); historyTable.border = "1"; historyTable.appendChild(historyTableBody); historyDiv.appendChild(historyTable); function ausgabe() { const calculation = `${window.document.Rechner.Display2.value}${window.document.Rechner.Display.value}`; const tr = document.createElement("TR"); const td = document.createElement("TD"); td.width = "75"; td.textContent = calculation; tr.appendChild(td); historyTableBody.appendChild(tr); } // Add keyboard support for better usability document.addEventListener('keydown', (e) => { const allowedKeys = ['0','1','2','3','4','5','6','7','8','9','.','+','-','*','/','(',')','Backspace','Enter']; if (allowedKeys.includes(e.key)) { e.preventDefault(); if (e.key === 'Backspace') backspace(); else if (e.key === 'Enter') { Ergebnis(); ausgabe(); } else add(e.key); } }); </script> <style type="text/css"> body { background-color: #FFFFE0; color: #000000; padding: 20px; } .calculator-container { display: flex; gap: 20px; } .calculator { border: 5px solid #000; padding: 10px; background-color: #C0C0C0; } .display { width: 100%; text-align: right; font-family: System, sans-serif; font-size: 1.2rem; padding: 5px; margin-bottom: 5px; } .button-grid { display: grid; grid-template-columns: repeat(4, 60px); gap: 2px; background-color: #E0E0E0; padding: 10px; } .button { width: 60px; text-align: center; font-family: System, sans-serif; font-size: 1rem; padding: 10px; cursor: pointer; } #Historie { border: 1px solid #000; padding: 10px; min-width: 250px; } </style> </head> <body> <div class="calculator-container"> <form name="Rechner" action="" onSubmit="Ergebnis();return false;"> <div class="calculator"> <div class="display-container"> <input type="text" name="Display2" class="display" readonly /> <input type="text" name="Display" class="display" readonly /> </div> <div class="button-grid"> <input type="button" class="button" value=" 7 " onClick="add('7')" /> <input type="button" class="button" value=" 8 " onClick="add('8')" /> <input type="button" class="button" value=" 9 " onClick="add('9')" /> <input type="button" class="button" value=" <- " onClick="backspace()" /> <input type="button" class="button" value=" 4 " onClick="add('4')" /> <input type="button" class="button" value=" 5 " onClick="add('5')" /> <input type="button" class="button" value=" 6 " onClick="add('6')" /> <input type="button" class="button" value=" + " onClick="add('+')" /> <input type="button" class="button" value=" 1 " onClick="add('1')" /> <input type="button" class="button" value=" 2 " onClick="add('2')" /> <input type="button" class="button" value=" 3 " onClick="add('3')" /> <input type="button" class="button" value=" - " onClick="add('-')" /> <input type="button" class="button" value=" . " onClick="add('.')" /> <input type="button" class="button" value=" 0 " onClick="add('0')" /> <input type="button" class="button" value=" = " onClick="Ergebnis();ausgabe()" /> <input type="button" class="button" value=" * " onClick="add('*')" /> <input type="button" class="button" value=" ( " onClick="add('(')" /> <input type="button" class="button" value=" ) " onClick="add(')')" /> <input type="reset" class="button" value=" C " /> <input type="button" class="button" value=" / " onClick="add('/')" /> </div> </div> </form> <div id="Historie"></div> </div> </body> </html>
Key Changes for Auto-Clear Functionality
- Added a global flag
shouldClearto track if we need to clear displays after a calculation. - Updated
Ergebnis()to setshouldClear = trueonce a calculation is completed. - Modified
add()to check the flag:- If
shouldClearis true and the input is a number/decimal point, it clears both displays. - Resets the flag immediately after clearing to ensure this only happens once per calculation.
- If
Additional Optimization Suggestions
- Readable Variable Names: Swapped some German names for English equivalents (e.g.,
nur_das→allowedChars) to make the code easier to follow. - Simplified Backspace: Removed the unnecessary loop in
backspace()—a singleslice(0, -1)call does the job. - Efficient History Log: Creates the history table once on page load instead of generating a new table for every calculation.
- Keyboard Support: Added event listeners to let users input via keyboard (numbers, operators, backspace, enter).
- Error Handling: Wrapped
eval()in a try-catch block to handle invalid expressions or division by zero gracefully. - Modernized CSS: Replaced nested tables with flexbox/grid for cleaner layout, and moved inline styles to a centralized stylesheet.
内容的提问来源于stack exchange,提问作者Yuuuhu
相关产品推荐
相关产品推荐

