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

点击导航链接时替换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-container before creating the new table. This ensures only the latest category's table is displayed.
  • Simplified filtering: Replaced the manual for loop with Array.filter() and Array.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:17:37