如何生成可自定义行列/宽高的JavaScript表格?代码问题求助
Fixing Your JavaScript Table Generator
Hey there! Let's walk through fixing your table generator code step by step—since you're new to coding, I'll break down each issue clearly so you understand what went wrong, then share the fully working version.
First, let's list the key issues in your original code:
- Syntax error in function definition: Your
generate()function was missing an opening{at the start, and had an extra closing}at the end. - Variable placement issues: You tried to use
num_rowsandnum_colsinside loops before defining them—we need to get those values before starting the loops. - Typos and missing elements:
document.create Elementhas an extra space (should bedocument.createElement)- You tried to append a
trelement that never got created withdocument.createElement('TR') - You had a typo:
wdithinstead ofwidthfor the input ID
- Default form behavior: Buttons inside a form default to submitting the form, which refreshes the page—we need to stop that so your table stays visible.
- Missing
deleteTablefunction: You referenced this function in your button but never wrote it.
Here's the fully corrected code:
<html> <body> <form> <p>No. of Cols: <input type="text" name="cols" id="cols" value="3" /></p> <p>No. of Rows: <input type="text" name="rows" id="rows" value="3" /> Sample Cell Data <input type="text" id="sample" /></p> <p>Cell Height (in pixels): <input type="text" id="height" value="50" /> Cell Width in pixels: <input type="text" id="width" value="100" /></p> <button onClick="generate(event)">Generate Table</button> <button onClick="deleteTable(event)">Clear Table</button> </form> <hr /> <div id="generatedTable"></div> <script> function generate(event) { // Prevent form from submitting and refreshing the page event.preventDefault(); // Get user input values first const numRows = parseInt(document.getElementById('rows').value); const numCols = parseInt(document.getElementById('cols').value); const cellHeight = document.getElementById('height').value; const cellWidth = document.getElementById('width').value; const sampleText = document.getElementById('sample').value || "Cell"; const tableContainer = document.getElementById("generatedTable"); // Clear existing table first before generating a new one tableContainer.innerHTML = ''; // Create table elements const table = document.createElement('TABLE'); table.border = '1'; const tableBody = document.createElement('TBODY'); table.appendChild(tableBody); for (let y = 0; y < numRows; y++) { // Create a new row for each iteration const tr = document.createElement('TR'); tableBody.appendChild(tr); for (let x = 0; x < numCols; x++) { const td = document.createElement('TD'); // Use user-provided width/height td.style.width = `${cellWidth}px`; td.style.height = `${cellHeight}px`; td.align = "center"; const cellID = `cell[${x},${y}]`; td.setAttribute("id", cellID); td.addEventListener("click", function(){cellClicked(this);}); // Use sample text if provided, else default to "Cell x,y" const cellText = sampleText ? `${sampleText} ${x},${y}` : `Cell ${x},${y}`; td.appendChild(document.createTextNode(cellText)); tr.appendChild(td); } } tableContainer.appendChild(table); } function deleteTable(event) { // Prevent form submission event.preventDefault(); const tableContainer = document.getElementById("generatedTable"); tableContainer.innerHTML = ''; } function cellClicked(cell) { // Example click behavior—you can expand this! alert(`You clicked cell: ${cell.id}`); } </script> </body> </html>
Key improvements explained:
- Fixed function syntax: Added the missing opening
{forgenerate()and removed the extra closing}. - Stopped form refresh: Added
event.preventDefault()to both button functions so clicking doesn't reload the page. - Proper variable setup: Got user input values before starting loops, and converted row/col counts to numbers with
parseInt()to avoid string comparison issues. - Created missing elements: Added
const tr = document.createElement('TR')inside the row loop to create each table row. - Fixed typos: Changed
wdithtowidthin the input ID, and fixed thecreateElementtypo. - Added
deleteTablefunction: Now the clear button works by emptying the table container. - Better user experience: Added default values for height/width so the table looks good even if the user doesn't input anything, and used the sample text input if provided.
- Updated container: Changed the
<p>tag for the table to a<div>—paragraph tags aren't meant for containing block elements like tables.
内容的提问来源于stack exchange,提问作者TryPenta
相关产品推荐
相关产品推荐

