簡體   English   中英

通過單擊另一個表中的單元格來刪除表中的列

[英]Delete column in a table by clicking cell in another table

我有兩個表:單行表位於多列表上方。 我想通過單擊位於此列正上方的單行表中的單元格來刪除多列表中的列。

我正在嘗試通過使用以下代碼來做到這一點:

$('.del-column').delegate('td', 'click', function() {
    var index = this.cellIndex;
    $(this).closest('.my-table').find('tr').each(function() {
        this.removeChild(this.cells[ index ]);
    });
});

其中.my-table是多列表,.del-column是單列表。 任何想法為什么它不起作用?

這是我嘗試執行的演示 這是圖像中的解釋。

首先,不贊成使用delegate() 您需要使用on()代替。

要解決您的實際問題,您需要修復所使用的DOM遍歷邏輯,因為.my-table不是單擊單元格的父級,而是父級div的同級子級。 您也可以使用:nth-child()選擇器來獲取列中的td元素,而無需循環。 嘗試這個

$('.del-column').on('click', '.del', function() {
  var index = this.cellIndex + 1;
  $(this).closest('div').siblings('div.canvas').find('table tr td:nth-child(' + index + ')').remove();
  $(this).remove();
});

工作實例

還要注意,HTML太復雜了。 使用單個表可以更簡單地實現它。 它還將幫助布局保持對齊。

$(this).closest('.my-table')將不起作用,因為.my-table不是.del-column的祖先。 嘗試如下。

$('.del-column').on('click', 'td', function() {
    var index = this.cellIndex;

    $('.my-table').find('tr').each(function() {
        this.removeChild(this.cells[ index ]);
    });
    $(this).remove();
});

更新場

您也可以像這樣遍歷它們,看看索引是否匹配。

var upperTable = document.querySelector(".del-column");
var lowerRows = document.querySelectorAll(".my-table tr")

function removeCorresponding(event) {
  upperIndex = event.target.cellIndex;
  lowerRows.forEach(function(row) {
    row.querySelectorAll("td").forEach(function(lowerCell, lowerIndex) {
      if (upperIndex === lowerIndex) {
        lowerCell.remove();
        event.target.remove()
      }
    });
  });
}

upperTable.querySelectorAll("td").forEach(function(cell, upperIndex) {
  cell.addEventListener("click", removeCorresponding);
});

https://jsfiddle.net/rt9oju8b/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM