点击导航链接时替换DOM旧内容,仅显示新内容的实现方案
Fix: Replace Old Table Instead of Appending New Ones
Got it, let's resolve that issue where clicking navigation links keeps adding new tables instead of switching to the selected category's content. The core problem here is that your current code appends a new table to the container every time, leaving all previous tables in the DOM. We just need to clear out the old content before adding the new table.
Modified Code
$(dataItems).on('click', 'li a', function (event) { event.preventDefault(); let id = $(this).attr('data-code'); // Filter the Assortments array for matching parent ID (simplified syntax) const childrenItems = Assortments .filter(item => item.AssortimentParentID === id) .map(item => item.Name); // Clear the container FIRST to remove old tables const container = document.querySelector(".deposit-container"); container.innerHTML = ""; // Draw the new table let perrow = 3, count = 0, table = document.createElement("table"), row = table.insertRow(); for (let i of childrenItems) { let cell = row.insertCell(); cell.innerHTML = i; count++; if (count % perrow === 0) { row = table.insertRow(); } } // Add the new table to the empty container container.appendChild(table); })
Key Changes Explained
- Cleared the container first: Added
container.innerHTML = "";to wipe out any existing content in.deposit-containerbefore creating the new table. This ensures only the latest category's table is displayed. - Simplified filtering: Replaced the manual
forloop withArray.filter()andArray.map()for cleaner, more readable code (this does the exact same job as your original loop—just more concise). - Cached the container element: Stored the container reference in a variable to avoid querying the DOM twice, a small but helpful performance tweak.
If you prefer to stick with jQuery syntax for consistency, you could swap the container clearing line with:
$(".deposit-container").empty();
Either approach will ensure each click replaces the old table with the new one, instead of stacking them up.
内容的提问来源于stack exchange,提问作者Dipzera
相关产品推荐
相关产品推荐

