如何通过循环横向罗列文件夹名称?解决单元格内容覆盖问题
Hey there! Let's dig into why your folder names are getting overwritten in the same cell when you're trying to list them horizontally.
First off, the most common culprit here is that you're reusing the same single element/cell variable through every loop iteration instead of creating a new one for each folder name. That means every new folder just replaces the content of the existing spot, rather than adding a new adjacent cell.
Let's walk through a fix—adjust based on your setup (vanilla JS, framework, table, etc.):
1. Start with a parent container
First, make sure you have a parent element where you'll attach each new folder entry. For a basic horizontal list, your HTML might look like this:
<div id="folder-list-container"></div>
2. Rewrite your loop logic
Instead of updating the same element over and over, create a new element for every folder and append it to the parent. Here's a vanilla JS example:
// Replace this with your actual folder name array const folderNames = ["Project Docs", "Assets", "Backup", "Temp Files"]; const container = document.getElementById("folder-list-container"); folderNames.forEach(folder => { // Create a new element for each folder const folderItem = document.createElement("div"); // Add styling to make items sit horizontally (tweak as needed) folderItem.style.display = "inline-block"; folderItem.style.margin = "0 10px"; folderItem.style.padding = "6px 12px"; folderItem.style.border = "1px solid #ddd"; // Set the folder name as the element's content folderItem.textContent = folder; // Append the new item to the parent container container.appendChild(folderItem); });
3. If you're using an HTML table
If you're trying to populate table cells horizontally in a row, make sure you create a new <td> for each folder and append it to your target <tr>:
<table> <tr id="folder-row"></tr> </table>
const folderNames = ["Designs", "Code", "Tests"]; const targetRow = document.getElementById("folder-row"); folderNames.forEach(folder => { const newCell = document.createElement("td"); newCell.textContent = folder; targetRow.appendChild(newCell); });
Quick audit of your existing code
Look for lines that look like this—this is what's causing the overwrite:
// ❌ Bad: Updates the same element every loop document.getElementById("single-cell").textContent = folder;
Swap that out for creating a new element each time and appending it to your parent container, and you'll see each folder name sit side-by-side as expected.
内容的提问来源于stack exchange,提问作者I. Я. Newb

