在飞行中删除所选表格的第一列

时间:2017-05-11 01:18:40

标签: javascript jquery

您能否请一看这个片段,让我知道如何动态修剪(删除第一列)所选表格并将其附加到#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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

我会将此添加到事件处理程序:

files

答案 1 :(得分:0)

我在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();
});