使用 jQuery 删除动态添加的表

问题描述 投票:0回答:1

如何删除使用 jQuery 动态添加到页面的整个表格?当用户单击开始按钮时,将创建一个表并添加数据。再次单击同一按钮时,表格和数据应被删除并替换为新数据。

首先,使用

remove()
并不会删除整个表格。 其次,当再次单击该按钮时,会附加(添加)一个包含数据的新表。所以网页上并排有两个表格。


async function fillTable() {
  // create thead, tbody, and tds
  // fill the thead and tbody
}

async function setupAndStart() {
  // UNIMPLEMENTED
  $("#jeopardy").remove();

  showLoadingView();

  // make HTML table
  const $gameBoard = $("<table></table>");
  $gameBoard
    .attr("id", "jeopardy")
    .append($("<thead></thead>"))
    .append($("<tbody></tbody>"));

  $(".spinner").after($gameBoard);

  await fillTable();

  hideLoadingView();

}

$("#start-btn").on("click", setupAndStart);

我尝试

remove()
桌子,并清空
thead
tbody
tr
。但它不起作用,并且存在同样的问题。

提前感谢您的任何意见。

javascript html jquery
1个回答
0
投票

我建议替换 HTML 元素。删除 ID 为“#jeopardy”的元素可能会带来一些延迟。

 async function fillTable() {
  // create thead, tbody, and tds
  // fill the thead and tbody
}

async function setupAndStart() {

  showLoadingView();

  // make HTML table
  const $gameBoard = $("<table></table>");
  $gameBoard
    .attr("id", "jeopardy")
    .append($("<thead></thead>"))
    .append($("<tbody></tbody>"));

  // Replace the element
  $("#jeopardy").replaceWith($gameBoard);

  $(".spinner").after($gameBoard);

  await fillTable();

  hideLoadingView();

}

$("#start-btn").on("click", setupAndStart);
© www.soinside.com 2019 - 2024. All rights reserved.