纯JavaScript实现成绩录入表格:Average Score列表头显示但初始值为?的问题求助
Hey there! Let's fix your issue step by step. The main problems in your current code are:
- The Average Score column is hidden by default via CSS, so you can't see the initial "?"
- You're calculating and inserting the average immediately on submit instead of showing "?" first
- There's a minor property name mismatch (
physicalvsphysics) that could cause errors - The
showAvgandshowBestfunctions have incorrect logic for their intended tasks
Here's the corrected code with explanations:
Corrected HTML
<body> <h1 align="center">Class Marksheet</h1> <table align="center"> <tr> <td>Name:</td> <td><input name="name" id="name" type="text" /></td> </tr> <tr> <td>Math:</td> <td> <input name="math" min="0" max="10" id="math" type="number" /> </td> </tr> <tr> <td>Physics:</td> <td> <input name="physics" min="0" max="10" id="physics" type="number" /> </td> </tr> <tr> <td>Chemistry:</td> <td> <input name="chemical" min="0" max="10" id="chemical" type="number" /> </td> </tr> <td> <button type="button" onclick="score_table()">Submit</button> </td> </table> <div id="divTable" style="display: none;"> <table id="tableScore" border="5" align="center"> <tr> <th>No</th> <th>Name</th> <th>Math</th> <th>Physics</th> <th>Chemistry</th> <th>Average Score</th> </tr> </table> <button onclick="showAvg()">Calculate the average score</button> <button onclick="showBest()">Best student</button> </div> <script src="js/script.js"></script> </body>
Note: Moved the script tag to the end of the body to ensure DOM elements are loaded before JS runs, and fixed the table header structure (wrapped th elements in a tr tag).
Corrected JavaScript
var testScore = { name: "", math: 0, physics: 0, chemistry: 0, avg: 0 }; var rowCount = 1; // Show table and add student data on submit function score_table() { document.getElementById("divTable").style.display = "block"; // Gather input data testScore.name = document.getElementById("name").value; testScore.math = parseFloat(document.getElementById("math").value); testScore.physics = parseFloat(document.getElementById("physics").value); testScore.chemistry = parseFloat(document.getElementById("chemical").value); // Calculate average but store it instead of showing immediately testScore.avg = ((testScore.math + testScore.physics + testScore.chemistry) / 3).toFixed(2); // Clear input fields document.getElementById("name").value = ""; document.getElementById("math").value = ""; document.getElementById("physics").value = ""; document.getElementById("chemical").value = ""; // Insert new row var table = document.getElementById("tableScore"); var row = table.insertRow(rowCount); // Create cells var numberCell = row.insertCell(0); var nameCell = row.insertCell(1); var mathCell = row.insertCell(2); var physicsCell = row.insertCell(3); var chemistryCell = row.insertCell(4); var avgCell = row.insertCell(5); // Populate cells numberCell.innerHTML = rowCount; nameCell.innerHTML = testScore.name; mathCell.innerHTML = testScore.math; physicsCell.innerHTML = testScore.physics; chemistryCell.innerHTML = testScore.chemistry; avgCell.innerHTML = "?"; // Show "?" initially avgCell.dataset.avg = testScore.avg; // Store calculated average in a data attribute rowCount++; } // Replace "?" with calculated average scores function showAvg() { var avgCells = document.querySelectorAll("#tableScore td:nth-child(6)"); avgCells.forEach(cell => { cell.innerHTML = cell.dataset.avg; }); } // Highlight rows where average >=8 function showBest() { var rows = document.querySelectorAll("#tableScore tr:not(:first-child)"); // Skip header row rows.forEach(row => { var avg = parseFloat(row.querySelector("td:nth-child(6)").innerHTML); // Check if avg is a valid number (in case showAvg hasn't been clicked yet) if (!isNaN(avg) && avg >= 8) { row.style.backgroundColor = "red"; } else { row.style.backgroundColor = ""; // Reset if not eligible } }); }
Key changes in JS:
- Fixed property name mismatch (
physical→physics) - Store the calculated average in a
data-avgattribute on the cell, while showing "?" initially - Rewrote
showAvgto replace "?" with the stored average - Improved
showBestto target rows correctly and handle cases where averages haven't been calculated yet
Corrected CSS
#divTable { text-align: center; width: 100%; } #tableScore { border-collapse: collapse; margin: 10px auto; } #tableScore th, #tableScore td { border: 5px solid black; padding: 8px; }
Removed the CSS that hid the Average Score column, since we want it visible with "?" from the start.
How it works:
- On submit, the student data is added to the table with "?" in the Average Score column, and the real average is stored in a hidden data attribute.
- Clicking "Calculate the average score" replaces all "?" values with the pre-calculated averages.
- Clicking "Best student" checks each average (whether calculated or not) and highlights rows with averages ≥8 in red.
内容的提问来源于stack exchange,提问作者user18181493
相关产品推荐
相关产品推荐

