【问题标题】:Delete Dynamic HTML table using table id?使用表格 ID 删除动态 HTML 表格?
【发布时间】:2020-04-26 15:44:28
【问题描述】:

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

【问题讨论】:

  • 您是否使用debugger 关键字调试过代码?并检查为什么按钮onclick,jquery $('table').on('click' 事件处理程序没有被调用?
  • 应该是 $("#" + tbl).remove();工作小提琴:jsfiddle.net/gr1cpjbo

标签: javascript html jquery dom


【解决方案1】:

虽然您正在获取表 id 的值,但需要在选择器中使用带有前导 # 的 jquery 正确引用它。

改变这个:

$(tbl).remove(); 

...到:

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

然后桌子被移除。

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2013-02-12
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多