简体   繁体   English

事件侦听器,JavaScript

[英]Event listeners, JavaScript

How do I make new content show in my DOM everytime I click a nav link and delete the old one.每次单击导航链接并删除旧内容时,如何在 DOM 中显示新内容。 I get the content one after another when clicking, I want to delete the old one, and show the one I clicked and so on.我点击的时候一个接着一个的获取内容,我想删除旧的,显示我点击的内容等等。 I'm using an array from a database.我正在使用数据库中的数组。 This is the code:这是代码:

$(dataItems).on('click', 'li a', function (event) {
  event.preventDefault();
  let id = $(this).attr('data-code'); // sort them by their data-code

  const childrenItems = []; // push the sorted array items from db to this array
  for (let i = 0; i < Assortments.length; i++) { // This is the array from DB
    if (Assortments[i].AssortimentParentID == id) {
      childrenItems.push(Assortments[i].Name);
    }
  }

  //draw html table
  let perrow = 3, // 3 items per row
       count = 0, // flag for current cell
       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();
    }
  }
  document.querySelector(".deposit-container").appendChild(table);


})

prnt.sc/rdnavd - this is how it looks, as you can see there's 2 tables, I clicked on 2 different categories, I want when clicking a category to show only one table and delete the other clicked before. prnt.sc/rdnavd - 这是它的外观,你可以看到有 2 个表格,我点击了 2 个不同的类别,我希望在点击一个类别时只显示一个表格并删除之前点击的另一个表格。

On this line:在这一行:
document.querySelector(".deposit-container").appendChild(table);

try replacing appendChild to innerHTML .尝试将appendChild替换为innerHTML Append will just keep on adding the element instead of replacing it. Append 只会继续添加元素而不是替换它。

Revised line:修改后的线路:
document.querySelector(".deposit-container").innerHTML = table;

EDIT:编辑:

If the above didn't work.如果上述方法不起作用。 Try resetting the child node.尝试重置子节点。

Replace document.querySelector(".deposit-container").appendChild(table);替换document.querySelector(".deposit-container").appendChild(table); with the below:与以下:

let parent = document.querySelector(".deposit-container");

while(parent.firstChild){
  parent.removeChild(parent.firstChild);
}

parent.appendChild(table);

Let me know if this helps...让我知道这是否有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM