JavaScript中多Prompt函数收集信息显示到Div的报错及解决
Let's break down what's going wrong and fix it step by step:
1. Why you're getting the "Cannot set property 'innerHTML' of null" error
Your financialInfoDisplay() function is called immediately when the script runs—before the page finishes loading. At that point, the #infoDisplay div hasn't been rendered in the DOM yet, so getElementById('infoDisplay') returns null, causing the error.
2. Why prompts aren't popping up as expected
The prompt functions (namePrompt, depositAmountPrompt, etc.) are tied to button clicks via event listeners set up in init(), which runs after the page loads. Your initial call to financialInfoDisplay() doesn't trigger these prompts—it just tries to display the (undefined) global variables before any input is collected.
3. Fixing the "overwriting content" issue
When you set innerHTML = ... directly in each prompt function, you're replacing the entire content of the div. Instead, we can rebuild the full display string every time new info is added, so all collected data stays visible.
Corrected Code
Here's the adjusted code that fixes all these issues:
// GLOBAL VARIABLES (initialized to empty strings to avoid undefined values) var userWithdrawal = "", userName = "", depositAmount = ""; // GETS ELEMENT FROM DOM (reusable helper function) var $ = function (id) { "use strict"; return window.document.getElementById(id); }; // GETS USER NAME AND UPDATES DISPLAY function namePrompt () { "use strict"; userName = window.prompt("Please enter your name") || ""; updateDisplay(); return userName; } // GETS DEPOSIT AMOUNT AND UPDATES DISPLAY function depositAmountPrompt () { "use strict"; depositAmount = window.prompt("Please enter the amount of money you would like to deposit") || ""; updateDisplay(); return depositAmount; } // GETS WITHDRAWAL AMOUNT AND UPDATES DISPLAY function withdrawalAmount () { "use strict"; userWithdrawal = window.prompt("Please enter the amount of money you would like to withdraw from your account") || ""; updateDisplay(); return userWithdrawal; } // SAFELY UPDATES THE DISPLAY DIV WITH ALL COLLECTED INFO function updateDisplay() { "use strict"; var infoDisplay = $('infoDisplay'); // Only proceed if the element exists (avoids null errors) if (infoDisplay) { // Build a clean display string with all collected data var displayText = ""; if (userName) displayText += `Name: ${userName}<br>`; if (depositAmount) displayText += `Deposit Amount: ${depositAmount}<br>`; if (userWithdrawal) displayText += `Withdrawal Amount: ${userWithdrawal}`; infoDisplay.innerHTML = displayText; } } // HANDLES ALL EVENT LISTENERS function init() { "use strict"; $('nameBtn').addEventListener("click", namePrompt); $('depositBtn').addEventListener("click", depositAmountPrompt); $('withdrawlBtn').addEventListener("click", withdrawalAmount); } // RUN INIT AFTER PAGE LOADS (ensures DOM elements exist before we interact with them) window.addEventListener("load", init);
<style> body { width: 500px; margin: 0 auto; } #infoDisplay { border: 3px solid black; height: 250px; padding: 10px; } </style> <body> <button type="button" id="nameBtn">Name</button> <button type="button" id="depositBtn">Deposit</button> <button type="button" id="withdrawlBtn">Withdraw</button> <div id="infoDisplay"></div> </body>
Key Changes Made:
- Removed the immediate call to
financialInfoDisplay()that was causing the null error. - Renamed the display function to
updateDisplay()and added checks to ensure the DOM element exists before modifying it. - Added
updateDisplay()calls after each prompt is answered, so the display refreshes automatically when new info is entered. - Built the display string from scratch each time using all current global variable values—no more overwriting content.
- Initialized global variables to empty strings to avoid showing "undefined" in the display.
- Fixed a typo in "withdrawal" (you had "withdrawl" in the button text and function name—optional, but improves consistency).
Now when you click each button, the prompt will pop up, and the #infoDisplay div will show all collected information without overwriting previous entries.
内容的提问来源于stack exchange,提问作者Aj96

