基于HTML和JavaScript实现用户输入数字倒计时功能报错求助
Fixing Your Auction Countdown Error
Hey there! Let's break down why you're seeing that "textContent cannot be null" error and get your countdown working properly.
The Issues in Your Code
- Incorrect selector for
getElementById: You useddocument.getElementById("#inputvalue")— butgetElementByIdexpects just the raw ID string, no#prefix. Adding the#means the browser can't find the element, so it returnsnull, hence the error. - Wrong property for input elements:
<input>tags store their content in thevalueproperty, nottextContent.textContentis for plain text elements like<p>or<div>. - Bonus: You likely want to update the displayed price, not the input box: Your flow has users submit a price to show in the
<p>tag — the countdown should probably update that displayed value instead of modifying the input field (though I'll show how to do either if needed).
Corrected JavaScript Code
Here's the fixed code, plus some improvements to make it more robust:
function submitPrice() { const priceSubmitted = $("#inputvalue").val(); $("#submittedprice").text(priceSubmitted); } function startAuction() { // Get the submitted price from the <p> tag first (uses the committed value) let startingPrice = parseInt(document.getElementById("submittedprice").textContent); // Fallback to input value if the <p> tag is empty if (isNaN(startingPrice)) { startingPrice = parseInt(document.getElementById("inputvalue").value); } // If no valid number exists, exit early to avoid errors if (isNaN(startingPrice)) { alert("Please enter and commit a valid price first!"); return; } const bidCountdown = setInterval(function() { startingPrice--; // Update the displayed <p> tag with the new countdown value document.getElementById("submittedprice").textContent = startingPrice; // Uncomment this line if you also want to update the input box // document.getElementById("inputvalue").value = startingPrice; // Stop the countdown when it hits 0 and add a message if (startingPrice <= 0) { clearInterval(bidCountdown); document.getElementById("submittedprice").textContent = "Auction Ended!"; } }, 1000); }
Key Changes Explained
- Removed the
#fromgetElementByIdcalls so the browser can find your elements correctly. - Used
valuefor the input element andtextContentfor the<p>tag, matching their respective properties. - Pulled the starting price from the
<p>tag first, ensuring we use the price the user actually committed (not whatever's in the input box at countdown start). - Added checks for invalid numbers to prevent errors if the user tries to start the auction without committing a price.
- Added an end message when the countdown hits 0 for better user feedback.
内容的提问来源于stack exchange,提问作者Luke Litherland
相关产品推荐
相关产品推荐

