javascript - 使用表 ID 删除动态 HTML 表?

标签 javascript html jquery dom

我正在从一个表创建多个表(表 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(); 

然后表格被删除。

关于javascript - 使用表 ID 删除动态 HTML 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61443582/

相关文章:

javascript - 正则表达式匹配分隔符后的任何内容

html - 并非所有 CSS 样式类的属性都适用

javascript - jQuery Animate Left 和 Right 只发生一次

javascript - jquery hover 在 wordpress 中无法正常工作

jquery - jQuery 中的 ^= 选择器有什么作用?

javascript - 带有 Backbone.js 的 JS 模板系统

javascript - splinter 的视差卷轴

javascript - 不能通过引用 Angular 来 $filter 数组

javascript - 保存和加载日期本地存储

html - Winsock recv 给出乱码和有用的 html