如何为Chrome应用添加重置功能?附相关代码
Hey there! No worries at all—we all start somewhere, and this is a great question. Let's get that reset functionality working for your straw rocket speed calculator 😊
Step 1: Add a Reset Button to Your HTML
First, we'll add a reset button right next to your submit action. I'll also suggest using <button> instead of <a> for better semantics (these are action buttons, not links):
<!DOCTYPE html> <html> <head> <script src="calc.js"></script> </head> <body> <h1>Enter the time and distance the rocket traveled</h1> <input id="T" placeholder="Time (seconds)"> <input id="D" placeholder="Distance in feet"> <!-- Use buttons for clearer action intent --> <button id="submitBtn">Calculate Speed</button> <button id="resetBtn">Reset</button> <p id="O"></p> </body> </html>
I tweaked the heading and placeholder text slightly for clarity, but feel free to keep your original wording if you prefer!
Step 2: Write the Reset Function in calc.js
Next, we'll create a function that clears all input fields and the output display, plus add a small validation check to avoid weird errors in your calculation:
function calc() { var t = document.getElementById("T").value; var d = document.getElementById("D").value; // Basic validation to prevent NaN or division-by-zero errors if (!t || !d || isNaN(t) || isNaN(d) || d == 0) { document.getElementById("O").innerHTML = "Please enter valid numbers (distance can't be 0!)"; return; } var x = 0.681818; var fo = t / d; var o = fo * x; // Add units to make the output meaningful document.getElementById("O").innerHTML = "Rocket Speed: " + o.toFixed(2) + " mph"; }; // New reset function to clear all fields function resetApp() { // Empty input boxes document.getElementById("T").value = ""; document.getElementById("D").value = ""; // Clear the output text document.getElementById("O").innerHTML = ""; }; document.addEventListener('DOMContentLoaded', function() { var submitBtn = document.getElementById('submitBtn'); submitBtn.addEventListener('click', function() { calc(); }); // Attach click listener to the reset button var resetBtn = document.getElementById('resetBtn'); resetBtn.addEventListener('click', function() { resetApp(); }); });
What We Updated:
- Added a
resetApp()function that instantly clears all inputs and the output display - Added basic validation to
calc()to handle cases where users enter non-numbers or a distance of 0 - Swapped
<a>tags for<button>tags (more appropriate for interactive actions) - Added units to the output so users know exactly what the calculated number represents
- Made placeholder text more specific to guide user input
Testing It Out:
- Enter valid numbers and click "Calculate Speed"—you'll see the formatted speed display
- Click "Reset"—all fields will clear immediately, ready for your next calculation
This should work seamlessly in your Chrome app! Let me know if you run into any small snags.
内容的提问来源于stack exchange,提问作者Ethan P

