【问题标题】:Event listeners, JavaScript事件监听器,JavaScript
【发布时间】:2020-06-21 03:45:33
【问题描述】:

每次单击导航链接并删除旧链接时,如何在 DOM 中显示新内容。我点击的时候是一个接一个的获取内容,我想删除旧的,显示我点击的那个等等。 我正在使用数据库中的数组。 这是代码:

$(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 - 这是它的样子,你可以看到有 2 个表格,我点击了 2 个不同的类别,我希望在点击一个类别时只显示一个表格并删除之前点击的另一个。

【问题讨论】:

  • 我不明白为什么你需要这种代码。如果您需要为刚刚添加到 DOM 的新元素添加新的事件侦听器。只需定义像$('body').on('click', '#your-selector', function) 这样的监听器。如果您仍然需要按照自己的意愿进行操作。您可以使用MutationObserver 满足您的需求
  • prnt.sc/rdnavd - 这就是它的外观,你可以看到有 2 个表格,我点击了 2 个不同的类别,我希望在点击一个类别时只显示一个表格并删除之前点击的另一个表格.
  • 请提供 jsFiddle 或 codepen 的工作示例。那样会更容易找到解决方案。
  • 代码大概有400行,别以为我能做到。我唯一能提供的是上面的代码。谢谢!

标签: javascript jquery dom events listener


【解决方案1】:

在这条线上:
document.querySelector(".deposit-container").appendChild(table);

尝试将appendChild 替换为innerHTML。 Append 将继续添加元素而不是替换它。

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

编辑:

如果上述方法不起作用。尝试重置子节点。

document.querySelector(".deposit-container").appendChild(table); 替换为以下内容:

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

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

parent.appendChild(table);

如果这有帮助,请告诉我...

【讨论】:

  • 我在我的 DOM 中得到了 [object HTMLTableElement]。似乎不起作用。谢谢!
  • @Dipzera 对不起,我在用我的手机,如果上述方法不起作用,您可以尝试在重新附加表格之前删除节点的子节点 removeChild()
  • 喜欢在创建表之前?或之前:document.querySelector(".deposit-container").appendChild(table); ?
  • @Dipzera 是就在appendChild() 行之前
  • Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. - 我在控制台中收到此错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 2012-09-13
  • 2013-07-21
  • 2011-05-23
  • 2011-01-16
  • 1970-01-01
相关资源
最近更新 更多