[英]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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.