jquery 动态删除所选表的第一列

cgvd09ve  于 2023-10-17  发布在  jQuery
关注(0)|答案(2)|浏览(114)

我正在处理下面的片段。如何动态地修剪(删除第一列)所选表并将其追加到#output

$("#select-tbl").on("click", function(){
    $('#output').append( $("#tbl-box").html());
});
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

th:nth-child(1) {
    background-color: #dddddd;
}
td:nth-child(1) {
    background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="tbl-box">
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>
</div>
<br />
<button id="select-tbl"> Select Table</button>
<br />
<br />
<div id="output"> </div>
oipij1gg

oipij1gg1#

我会把它添加到事件处理程序中:

$('#output > table td:first-child').remove();
$('#output > table th:first-child').remove();
yxyvkwin

yxyvkwin2#

我在JS Bin上创建了demo。请检查一下。
基本上,我认为这个想法是检索第一列(带标题),并将其附加到output div,然后在原始表中删除它。下面是JavaScript代码:

$("#select-tbl").on("click", function(){
    // get the header of the first column
    var header = $('th:nth-child(1)').html();
    var table = $('<table></table>');
    table.append('<tr><th>' + header + '</th></tr>');
    // get each <td> element
    for (var i = 0; i < $("td:nth-child(1)").length; i++){
      var row = $('<tr></tr>');
      row.append('<td>' + $("td:nth-child(1)").eq(i).text() + '</td>');
      row.appendTo(table);
    }
    $('#output').append(table);
    // remove in the original table
    $('#tbl-box > table td:first-child').remove();
    $('#tbl-box > table th:first-child').remove();
});

相关问题