不,不需要硬编码。只需检查(在您的 td-click 处理程序中)该元素的某些同级元素是否已突出显示。例如,如果您分配一个类“.highlight”,查询将如下所示:
$(this).siblings('.highlight');
...这将只从同一行返回突出显示的元素。
更新:误读了您的问题,并认为您实际上需要突出显示水平列。如果您需要使用它是垂直的,请在您的查询中添加一些index
和:nth-child
$('td').click(function() {
var $this = $(this),
index = $this.index();
var $columnCells = $this.parents('table')
.find('tr td:nth-child(' + (index + 1) + ')');
$columnCells.toggleClass('highlight');
});
演示。
更新#2:这是(诚然,有点粗略)完整 col-highlighting 代码的示例:
$('td').click(function() {
var $this = $(this),
index = $this.index(),
$table = $this.parents('table'),
$rows = $table.find('tr'),
$columnCells = $rows.find('td:nth-child(' + (index + 1) + ')');
var $hiCells = $columnCells.filter('.highlight');
if ($hiCells.length) {
var thisRowIndex = $this.parent().index(),
$firstHiRow = $( $hiCells[0] ).parent(),
firstHiIndex = $firstHiRow.index(),
$lastHiRow = $( $hiCells[$hiCells.length - 1] ).parent(),
lastHiIndex = $lastHiRow.index();
if (thisRowIndex > lastHiIndex) {
$rows.slice(lastHiIndex, thisRowIndex + 1)
.find('td:nth-child(' + (index + 1) + ')').addClass('highlight');
} else if (thisRowIndex < firstHiIndex) {
$rows.slice(thisRowIndex, firstHiIndex)
.find('td:nth-child(' + (index + 1) + ')')
.addClass('highlight');
}
} else {
$table.find('td').removeClass('highlight');
$this.addClass('highlight');
}
});
演示。
如您所见,每次单击一个单元格时,我们都会获取该列中的所有单元格,然后检查它们的突出显示状态。如果其中一些被突出显示,我们得到第一个和最后一个突出显示的行,然后基本上对它们执行相同的操作:1)获取单击行和最后一个突出显示的行之间的所有行;2)获取同一列中的所有单元格,3)标记它们!如果此列中没有突出显示单元格,我们只需删除突出显示集,然后突出显示单击的单元格。
但是,如果所有列号都被缓存(例如,使用 'data-column' 属性),这可以大大简化。但我想,总的来说,方法还是一样的。