簡體   English   中英

使用表 ID 刪除動態 HTML 表?

[英]Delete Dynamic HTML table using table id?

我正在從一個表創建多個表(表 id = table6) 如果我從表 id ='table6' 創建了一個新表,我想使用它的表 id 刪除那個新生成的表。 我已將表 ID 分配給新生成的表。 我的代碼有什么問題? 我想刪除這個 HTML 表。 有什么提示嗎?

 var aggTableNum = 0; function generateAgg() { const originTable = document.getElementById('table6'); const baseRowTbl = originTable.querySelector('tbody tr'); let newTable = originTable.cloneNode(true); let newTbody = newTable.querySelector('tbody'); newTable.id = 'newAggTable' + ++aggTableNum; // for (i = 0; i < 0; i++) { // newTbody.appendChild(baseRowTbl.cloneNode(true)); // } newTable.querySelectorAll('input').forEach((element) => { element.value = ''; }); document.body.appendChild(newTable); } function tID() { $('table').on('click', 'button', function (e) { alert(e.delegateTarget.id); var tbl = e.delegateTarget.id; console.log(tbl); // if (tbl) tbl.parentNode.removeChild(tbl); $(tbl).remove(); }); }
 table { border-collapse: collapse; margin: 1em; } thead { background-color: lightblue; } td, th { border: solid grey 1px; padding: 1em; text-align: center; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button style="margin: 1%" onclick="generateAgg()">Generate New Table</button> <table id="table6"> <thead> <th colspan="6">Table</th> <tr> <th> Column 1 </th> <th> Column 2 </th> </tr> </thead> <tbody> <tr> <td> <input> </input> </td> <td><input> </input></td> </tr> <tr> <td> <button style="margin: 1%" onclick="tID()">delete </button> </td> </tr> </tbody> </table>

JsFiddle鏈接-> https://jsfiddle.net/shreekantbatale2/hn0286zd/8/

盡管您正在獲取表 id 的值,但需要使用 jquery 在選擇器中使用前導#正確引用它。

改變這個:

$(tbl).remove(); 

...至:

$('#' + tbl).remove(); 

然后桌子移除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM