JavaScript页面输出问题:点击游戏按钮无法显示胜负结果求助
Hey there! Let's get that win/lose result showing up on the page instead of just hiding in the console. The problem with document.write here is that once the page finishes loading, it overwrites the entire DOM—so your buttons would disappear right after you click them, which is definitely not what you want.
Here's a straightforward fix that adds a dedicated area for results and updates it dynamically:
Step 1: Add a Result Display Element to Your HTML
First, add a <div> below your buttons to hold the result text. This gives us a safe target to update without messing up the rest of the page:
<button id="button1" onclick="checkIsWin(1)" style="height: 200px; width: 200px; position: absolute; left: 33%; background-color: black; color: blue;">1</button> <button id="button2" onclick="checkIsWin(2)" style="height: 200px; width: 200px; position: absolute; right: 33%; background-color: black; color: red;">2</button> <!-- New result display area --> <div id="result" style="margin-top: 250px; text-align: center; font-size: 24px; font-weight: bold;"></div>
Step 2: Update Your JavaScript to Use the Result Element
Next, modify your JS to grab the result element, then update its content when a button is clicked. I also added a step to recalculate the winning button after each click—otherwise, the same button will stay the winner forever, which makes the game pretty boring!
// Grab our elements once when the script loads const button1 = document.getElementById('button1'); const button2 = document.getElementById('button2'); const resultElement = document.getElementById('result'); // Get the new result div const buttonsArray = ['button1', 'button2']; let winItem; // Generate a random winning button number (1 or 2) function getRandomItemNum(length) { // Using Math.floor + 1 is more intuitive for 1-based button numbering return Math.floor(Math.random() * length) + 1; } function recalculateWinItem() { winItem = getRandomItemNum(buttonsArray.length); } function checkIsWin(buttonNum) { // Determine the result text const resultText = buttonNum === winItem ? "You won! 🎉" : "You lose! 😢"; // Update the result element on the page resultElement.textContent = `Clicked button ${buttonNum}. ${resultText}`; // Pick a new winning button for the next round recalculateWinItem(); } // Set the first winning button when the page loads recalculateWinItem();
Key Changes Explained:
- We added a persistent
<div id="result">to display text without overwriting the page. - Instead of
console.log, we usetextContentto update the result div's text—this is the standard, clean way to modify text content on a page. recalculateWinItem()runs after each click so the winning button changes every round.- Switched to
const/letinstead ofvarfor better scoping (modern JS best practice).
Give this a try—now when you click a button, you'll see the result clearly displayed below the buttons!
内容的提问来源于stack exchange,提问作者Elguti




