在以下代码中:http://jsfiddle.net/ueP5U/1/
我有一个表,其中每个 td/th 成员都通过其 <tr>
给出了一个相对索引
var tableIterator = function(table, process) {
$.each(table.children(), function() { //cycle through thead,tbody,tfoot
$(this).children().each(function() { //cycle through thead, tbody, tfoot "tr"s
process.call($(this));
});
});
}
tableIterator($("table"), function() {
$(this).find("td,th").each(function() {
$(this).text("Index: " + $(this).index());
});
});
该表可以包含两个或多个标题,其中父标题获得更大的 colspan 并且底部标题通过提供相等数量的列来符合(即索引 4 有两个索引为 1 和 2 的子标题)。
我实际上想做的是创建父标题,选择它的所有“子项”(当然不是实际的 dom 子项),并根据所选列执行相同的操作。
我明白了逻辑:每个标题元素,需要找到它 previous sibling “ child ”索引,并将 colspan 的数量添加到它自己的 child ot 得到他们的索引(即索引 5[colspan=2],去索引4,找到它的最后一个 child (索引 1))并将 colspans 的数量添加到它的“ child ”中,这样他们就会有索引:2 和索引:3(+=1*colspan.val() 次)
“ child ”也是如此。
我假设我需要根据使用 jQuery.filter(return $("thead").findByColumn(2[or any other top header index])) 显示的内容创建一个包含绑定(bind)元素的对象数组
希望得到一些帮助,因为我什至开始这个都遇到了麻烦,非常欢迎通过单击突出显示、通过 max_width 隐藏或根据选择在列上运行内容的示例!
最佳答案
function iterTable(table, callback) {
// Keeps track of which indices are blocked by larger cells
var blocked = [];
$("thead,tbody,tfoot", table).each(function (groupIndex) {
var groupName = this.tagName;
$("tr", this).each(function (rowIndex) {
var colIndex = 0;
var blockedRow = blocked[0] || [];
$("td,th", this).each(function () {
var $cell = $(this);
var colSpan = parseInt($cell.prop("colspan")) || 1;
var rowSpan = parseInt($cell.prop("rowspan")) || 1;
// Skip all blocked cells
while (blockedRow[colIndex]) {
colIndex++;
}
callback(groupIndex, groupName, rowIndex, colIndex, $cell);
// Mark all sub-cells as blocked.
for (var i = 0; i < rowSpan; i++) {
for (var j = 0; j < colSpan; j++) {
if (!blocked[i]) blocked[i] = [];
blocked[i][colIndex+j] = true;
}
}
colIndex += colSpan;
});
// Pop the first element; We don't need it any more.
blocked.shift();
});
});
}
var columns = [];
iterTable($('table'), function (groupIndex, groupName, rowIndex, colIndex, $cell) {
$cell.text(groupName + " " + rowIndex + "," + colIndex);
if (groupName == "TBODY") {
// Save the cell into a specific column.
if (!columns[colIndex]) columns[colIndex] = [];
columns[colIndex][rowIndex] = $cell;
}
else { // THEAD or TFOOT
var colSpan = parseInt($cell.prop("colspan")) || 1;
$cell.click(function () {
// Toggle the background for the column under the header.
for (var i = 0; i < colSpan; i++) {
$.each(columns[colIndex+i], function () {
$(this).toggleClass('selected');
});
}
});
}
});
关于javascript - 表索引和成员绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13273316/