gpt4 book ai didi

javascript - 隐藏表列 ondblclick

转载 作者:行者123 更新时间:2023-11-30 10:46:02 24 4
gpt4 key购买 nike

我有一个表格,我想在双击某列时隐藏该列。

隐藏列的代码几乎都在 Stack Overflow 周围。我只需要提示如何/在何处添加 ondblclick事件,以便我可以检索 <td> 的身份在 <table> 内.

最佳答案

这里有两个应该有效的解决方案。一种使用 jQuery 完成,另一种仅使用标准 Javascript。

http://jsfiddle.net/GNFN2/2/

// Iterate over each table, row and cell, and bind a click handler
// to each one, keeping track of which column each table cell was in.
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++) {
var rows = tables[i].getElementsByTagName('tr');
for (var j = 0; j < rows.length; j++) {
var cells = rows[j].getElementsByTagName('td');
for (var k = 0; k < cells.length; k++) {
// Bind our handler, capturing the list of rows and colum.
cells[k].ondblclick = column_hide_handler(rows, k);
}
}
}

// Get a click handler function, keeping track of all rows and
// the column that this function should hide.
function column_hide_handler(rows, col) {
return function(e) {
// When the handler is triggered, hide the given column
// in each of the rows that were found previously.
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].getElementsByTagName('td');

if (cells[col]) {
cells[col].style.display = 'none';
}
}
}
}

有了 jQuery,它就干净多了。此方法还使用事件冒泡,因此您无需将事件处理程序分别绑定(bind)到每个表格单元格。

http://jsfiddle.net/YCKZv/4/

// Bind a general click handler to the table that will trigger
// for all table cells that are clicked on.
$('table').on('dblclick', 'td', function() {
// Find the row that was clicked.
var col = $(this).closest('tr').children('td').index(this);
if (col !== -1) {
// Go through each row of the table and hide the clicked column.
$(this).closest('table').find('tr').each(function() {
$(this).find('td').eq(col).hide();
});
}
});

关于javascript - 隐藏表列 ondblclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8238626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com