You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成可自定义行列/宽高的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_rows and num_cols inside loops before defining them—we need to get those values before starting the loops.
  • Typos and missing elements:
    • document.create Element has an extra space (should be document.createElement)
    • You tried to append a tr element that never got created with document.createElement('TR')
    • You had a typo: wdith instead of width for 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 deleteTable function: 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:

  1. Fixed function syntax: Added the missing opening { for generate() and removed the extra closing }.
  2. Stopped form refresh: Added event.preventDefault() to both button functions so clicking doesn't reload the page.
  3. Proper variable setup: Got user input values before starting loops, and converted row/col counts to numbers with parseInt() to avoid string comparison issues.
  4. Created missing elements: Added const tr = document.createElement('TR') inside the row loop to create each table row.
  5. Fixed typos: Changed wdith to width in the input ID, and fixed the createElement typo.
  6. Added deleteTable function: Now the clear button works by emptying the table container.
  7. 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.
  8. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:25:06