如何用JavaScript统计标点符号并在HTML中展示结果
Hey there! Let's fix up your punctuation counter program step by step. I noticed a few issues in your code that are keeping it from working correctly—let's go through them and get it running smoothly.
Key Issues in Your Original Code
- The
doCountfunction declares parameters but doesn't use them, then redefines the same variables inside the function (which is redundant and causes confusion). - You tried to get the input value with
.text—for<input>elements, we need to use.valueto access user input. - The
countvariable wasn't initialized, so trying to increment it would result inNaN. - Checking if a character matches the entire
punctarray directly (sentence1[i] == punct) doesn't work—we need to check if the character exists inside the array. - You placed
return countbefore updating the DOM element, which means the line settinginnerHTMLwould never run (sincereturnexits the function immediately).
Fixed Code
First, here's the updated HTML file (index.html):
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Punctuation Marks Counter</title> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <h1>Punctuation Marks Counter!</h1> <input type="text" id="sentence1" class="box1" placeholder="Type your sentence here..."> <button onclick="doCount();">Let's Count!</button> <p id="ans"></p> <!-- Load JS at the end of <body> to ensure DOM elements exist when code runs --> <script type="text/javascript" src="index.js"></script> </body> </html>
Next, the external JavaScript file (index.js):
function doCount() { // Get user input from the text box const inputText = document.getElementById('sentence1').value; // Define the punctuation marks we want to count const punctuation = [".", ",", "!", "?"]; // Initialize counter to 0 let count = 0; // Loop through each character in the input text for (let i = 0; i < inputText.length; i++) { // Check if current character is in our punctuation array if (punctuation.includes(inputText[i])) { count++; } } // Display the result on the page document.getElementById("ans").textContent = `Total punctuation marks: ${count}`; }
What Changed & Why
- Removed unused function parameters and directly fetched input values inside the function for clarity.
- Switched from
.textto.valueto correctly access input content. - Initialized
countto 0 to avoid invalid number errors. - Used
punctuation.includes(inputText[i])to properly check if a character is a target punctuation mark. - Moved the JS script to the end of the
<body>tag—this ensures all DOM elements are loaded before the JavaScript runs, preventing "element not found" errors. - Added a placeholder to the input box to improve user experience.
内容的提问来源于stack exchange,提问作者user9347860
相关产品推荐
相关产品推荐

