JS表格生成器仅生成一行问题求助及appendChild用法咨询
appendChild() Hey there! Let's start with fixing your table issue first, then break down how appendChild() works since you're new to it—this should clear things up.
Why You're Only Getting One Row
The most common reason for this problem is that you're reusing the same <tr> (table row) element across your loop instead of creating a new one for each row.
Here's the key thing to remember: A single DOM element can only exist in one place in the DOM tree at a time. If you create one <tr> outside your row loop and keep appending cells to it, you'll end up with one row full of all your cells. Or if you try to append the same <tr> multiple times, appendChild() will just move it from its current position instead of making a copy.
Correct Example Code
Here's how to adjust your code to generate the right number of rows and columns:
var submit = document.getElementById("smit"); var irow = document.getElementById("irow"); var icol = document.getElementById("icol"); submit.addEventListener('click', function() { // Get the input values (parse to numbers) const numRows = parseInt(irow.value); const numCols = parseInt(icol.value); // Create a new table element const table = document.createElement('table'); table.border = '1'; // Add border for visibility // Loop through each row for (let r = 0; r < numRows; r++) { // Create a NEW row for each iteration (critical!) const row = document.createElement('tr'); // Loop through each column in the current row for (let c = 0; c < numCols; c++) { const cell = document.createElement('td'); cell.textContent = `(${r+1}, ${c+1})`; // Add your (x,y) value row.appendChild(cell); // Add cell to the current row } // Add the completed row to the table table.appendChild(row); } // Add the table to your page (adjust the parent element as needed) document.body.appendChild(table); });
All the Ways to Use appendChild()
Now let's cover the different use cases for appendChild() to help you get comfortable with it:
Add a newly created element to a parent
This is the most common use case—create an element, then attach it to an existing parent in the DOM:const parentDiv = document.getElementById('my-container'); const newButton = document.createElement('button'); newButton.textContent = 'Click Me'; parentDiv.appendChild(newButton);Move an existing DOM element
If you pass an element that's already in the DOM toappendChild(), it will be removed from its current position and added to the new parent. No duplication happens here:const oldParent = document.getElementById('old-box'); const newParent = document.getElementById('new-box'); const myElement = document.getElementById('move-me'); newParent.appendChild(myElement); // Element moves from oldParent to newParentAdd a text node directly
You can create and append raw text nodes (though usingtextContentis more common now):const text = document.createTextNode('This is a standalone text node'); document.body.appendChild(text);Batch-add elements with DocumentFragment
When adding multiple elements, using aDocumentFragmentlets you avoid multiple DOM reflows (which improves performance). The fragment acts as a temporary container, and when you append it, all its children are added at once:const fragment = document.createDocumentFragment(); for (let i = 0; i < 3; i++) { const listItem = document.createElement('li'); listItem.textContent = `Item ${i+1}`; fragment.appendChild(listItem); } document.getElementById('my-list').appendChild(fragment);Chain calls (since
appendChild()returns the added element)
You can chain operations becauseappendChild()gives you back the element you just added:// Create a div, add a span to it, then set the span's text const span = document.createElement('div') .appendChild(document.createElement('span')); span.textContent = 'Chained content'; document.body.appendChild(span.parentElement);
内容的提问来源于stack exchange,提问作者user9623870

