三数最大值查找程序故障求助:文件关联问题排查
Hey there! Let's break down why your program isn't running and fix it step by step:
The Critical Error in Your JavaScript
The main issue is a tiny but impactful oversight in the first line of your JS code. Take a look:
// ❌ Wrong: getElementById isn't a global function let pressedKey = getElementById("button");
getElementById() is a method that belongs to the document object—you can't call it on its own. This throws a reference error that stops your entire script from executing before it even gets to the click event logic.
Fixed JavaScript Code
Here's the corrected JS with that fix, plus an extra check for invalid inputs (to handle cases where users enter non-numeric values, which would break your current logic):
// ✅ Correct: Use document.getElementById() let pressedKey = document.getElementById("button"); pressedKey.addEventListener("click",function() { let num1 = Number(document.getElementById("num1").value); let num2 = Number(document.getElementById("num2").value); let num3 = Number(document.getElementById("num3").value); // Add this to catch non-numeric inputs if (isNaN(num1) || isNaN(num2) || isNaN(num3)) { window.alert("Oops! Please enter valid numbers for all three fields."); return; // Stop the function here if inputs are invalid } if (num1 > num2 && num1 > num3) { window.alert(num1 + " is the greatest!"); } else if (num2 > num1 && num2 > num3) { window.alert(num2 + " is the greatest!"); } else { window.alert(num3 + " is the greatest!"); } });
Quick Check for File Paths
Make sure your greatestNumber.js file is saved in the same folder as your HTML file. If you put it in a subfolder (like a js/ directory), update your script tag to match the path:
<script src="js/greatestNumber.js"></script>
Minor HTML Tweak (Optional)
Your HTML works perfectly fine, but just a quick standardization note: HTML input tags are self-closing, so you don't need </input>—you can write them like this instead (it's more widely accepted practice):
Enter number one: <input type="text" id="num1"><br> Enter number two: <input type="text" id="num2"><br> Enter number three: <input type="text" id="num3"><br>
With these fixes, your program should run smoothly when you click the "OK" button!
内容的提问来源于stack exchange,提问作者Lubak

