如何使用jquery通过单击单元格来删除列

How to delete a column using jquery by clicking on a cell?

本文关键字:单元格 删除列 单击 何使用 jquery      更新时间:2023-09-26

我有一个表,我可以随时向其中添加列。每个列的顶部都有一个[X]图标,当用户单击它时,我需要删除整个列。

我创建了一个Fiddler页面,向您展示我所做的一切。

正如你所看到的,我在顶部有[X]图标,当我单击它时,它正在删除表中的第三列,因为我指定了一个固定列,即3。但我需要能够删除当前列,而不是第三列。

如何确定当前列是什么,并删除表中与正确位置匹配的每个tr

可以试试这样的东西:

$('.removeMe').click(function() {
    var indexToRemove = $(this).index();
    $(".defaultTable tbody tr").each(function() {
        $(this).find("td:eq("+indexToRemove+")").remove();
     });
});

编辑:

这里有一个fiddle,它将删除它们、标题以及任何动态创建的列。它将jQuery的.on()方法与委托事件一起使用,这样即使是动态创建的元素也会添加此事件侦听器。.click()是一个直接绑定,只将其绑定到已经存在的元素,因此新创建的元素不会将事件侦听器绑定到它们。

Fiddle:http://jsfiddle.net/stevenelberger/dsL31yek/

您可以使用https://api.jquery.com/nth-child-selector/:

$('#testTable1').on('click', '.removeMe', function () {
   $(".defaultTable thead tr th:nth-child(" + ($(this).index() + 1) + ")").remove();
   $(".defaultTable tbody tr td:nth-child(" + ($(this).index() + 1) + ")").remove();
});

代码段:

$(document).ready(function () {
  $('.defaultTable').dragtable();
  $('#test1').click(function () {
    $("#testTable1 > thead > tr").each(function () {
      $(this).append('<th>New Column</th>');
    });
    $("#testTable1 > tbody > tr").each(function (i, e) {
      if (i == 0) {
        $(this).append('<td class="removeMe">[X]</td>');
      } else {
        $(this).append('<td>New cell in the column</td>');
      }
    });
    $('.defaultTable').removeData().dragtable();
  });
  $('#testTable1').on('click', '.removeMe', function () {
    $(".defaultTable thead tr th:nth-child(" + ($(this).index() + 1) + ")").remove();
    $(".defaultTable tbody tr td:nth-child(" + ($(this).index() + 1) + ")").remove();
  });
  $('.defaultTable').removeData().dragtable();
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://akottr.github.io/css/akottr.css" rel="stylesheet"/>
<link href="http://akottr.github.io/css/reset.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="//rawgithub.com/akottr/dragtable/master/dragtable.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="//rawgithub.com/akottr/dragtable/master/jquery.dragtable.js"></script>
<!-- only for jquery.chili-2.2.js -->
<script src="//code.jquery.com/jquery-migrate-1.1.1.js"></script>
<script type="text/javascript" src="//akottr.github.io/js/jquery.chili-2.2.js"></script>
<div class="sample">
    <button type="button" id="test1">Add column</button>
    <div class="demo">
        <h4>demo</h4>
        <div class="demo-content">
            <table class="defaultTable sar-table" id="testTable1">
                <thead>
                <tr>
                    <th>TIME</th>
                    <th>%user</th>
                    <th>%nice</th>
                    <th>%system</th>
                    <th>%iowait</th>
                    <th>%idle</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td class="removeMe">[X]</td>
                    <td class="removeMe">[X]</td>
                    <td class="removeMe">[X]</td>
                    <td class="removeMe">[X]</td>
                    <td class="removeMe">[X]</td>
                    <td class="removeMe">[X]</td>
                </tr>
                <tr>
                    <td>12:10:01 AM</td>
                    <td>28.86</td>
                    <td>0.04</td>
                    <td>1.65</td>
                    <td>0.08</td>
                    <td>69.36</td>
                </tr>
                <tr>
                    <td>12:20:01 AM</td>
                    <td>26.54</td>
                    <td>0.00</td>
                    <td>1.64</td>
                    <td>0.08</td>
                    <td>71.74</td>
                </tr>
                <tr>
                    <td>12:30:01 AM</td>
                    <td>29.73</td>
                    <td>0.00</td>
                    <td>1.66</td>
                    <td>0.09</td>
                    <td>68.52</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

var index = $(this).index();
$(".defaultTable tr").each(function() {
     //remove body
     $(this).find("td:eq("+index+")").remove();
     //and head
     $(this).find("th:eq("+index+")").remove();
});

演示

您可以尝试从表中获取列号

$('.removeMe').click(function(){
var colNum = $(this).parent().children().index($(this));// getting the column number
console.log(colNum);
$(".defaultTable tbody tr").each(function() {
$(this).find("td:eq("+colNum+")").remove();
});                         
});

添加我的许多答案:

工作示例:

http://jsfiddle.net/Twisty/h0asbe6o/

jQuery

function removeColumn(n, o) {
  o = (o != "undefined") ? o : $("#testTable1");
  console.log("Removing Column '" + o.find("thead tr th:eq(" + n + ")").text() + "' (" + n + ") from " + o.attr("id"));
  o.find("tr").each(function(k, e) {
    $(e).find("th:eq(" + n + ")").empty().remove();
    $(e).find("td:eq(" + n + ")").empty().remove();
  });
  return true;
}

此外,您还想修复一些创建问题:

$(document).ready(function() {
  $('.defaultTable').dragtable();
  $('#test1').click(function() {
    $("#testTable1 > thead > tr").append('<th>New Column</th>');
    $("#testTable1 > tbody > tr").each(function(key, el) {
      if (key == 0) {
        var rm = $("<span>", {
            class: "removeMe"
          })
          .html("[X]")
          .click(function() {
            removeColumn($(this).index());
            $(this).remove();
          });
        rm.appendTo(el);
      } else {
        $(el).append('<td>New cell in the column</td>');
      }
    });
    $('.defaultTable').removeData().dragtable();
  });
  $('.removeMe').on("click", function() {
    removeColumn($(this).index());
    $('.defaultTable').removeData().dragtable();
  });
});

这将正确地创建新列,并允许您删除静态或动态创建的元素。

编辑

如果你想改进UI,你可以这样做:

http://jsfiddle.net/Twisty/h0asbe6o/4/

HTML

<div class="sample">
  <button type="button" id="test1">Add column</button>
  <div class="demo">
    <h4>demo</h4>
    <div class="demo-content">
      <table class="defaultTable sar-table" id="testTable1">
        <thead>
          <tr>
            <th><span class="cTitle handle">TIME</span><span class="removeMe">[x]</span></th>
            <th><span class="cTitle handle">%user</span><span class="removeMe">[x]</span></th>
            <th><span class="cTitle handle">%nice</span><span class="removeMe">[x]</span></th>
            <th><span class="cTitle handle">%system</span><span class="removeMe">[x]</span></th>
            <th><span class="cTitle handle">%iowait</span><span class="removeMe">[x]</span></th>
            <th><span class="cTitle handle">%idle</span><span class="removeMe">[x]</span></th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>12:10:01 AM</td>
            <td>28.86</td>
            <td>0.04</td>
            <td>1.65</td>
            <td>0.08</td>
            <td>69.36</td>
          </tr>
          <tr>
            <td>12:20:01 AM</td>
            <td>26.54</td>
            <td>0.00</td>
            <td>1.64</td>
            <td>0.08</td>
            <td>71.74</td>
          </tr>
          <tr>
            <td>12:30:01 AM</td>
            <td>29.73</td>
            <td>0.00</td>
            <td>1.66</td>
            <td>0.09</td>
            <td>68.52</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

CSS

.removeMe {
  font-size: .65em;
  float: right;
  cursor: pointer;
  margin-top: -0.5em;
  color: #aaa;
}
.removeMe:hover {
  color: #222;
}

jQuery

function removeColumn(n, o) {
  o = (o != "undefined") ? o : $("#testTable1");
  o.find("tr").each(function(k, e) {
    if (k == 0) {
      $(e).find("th").eq(n).hide("slow").remove();
    } else {
      $(e).find("td").eq(n).hide("slow").remove();;
    }
  });
  return true;
}
var dragOptions = {
  dragHandle: '.handle'
};
$(document).ready(function() {
  $('.defaultTable').dragtable(dragOptions);
  $('#test1').click(function() {
    var head = $("<th>").html("<span class='cTitle handle'>New Column</span>");
    var rm = $("<span>", {
        class: "removeMe"
      })
      .html("[X]")
      .click(function() {
        removeColumn($(this).parent().index());
        $(this).remove();
      });
    rm.appendTo(head);
    head.appendTo("#testTable1 > thead > tr");
    $("#testTable1 > tbody > tr").each(function(key, el) {
      $(el).append('<td>New Cell</td>');
    });
    $('.defaultTable').removeData().dragtable(dragOptions);
  });
  $('.removeMe').on("click", function() {
    removeColumn($(this).parent().index());
    $('.defaultTable').removeData().dragtable(dragOptions);
  });
});