我有以下代码使用上下文菜单插件将行添加到表中,因此您可以右键单击要在下面添加行的单元格。
(function($){
function scanTable( $table ) {
var m = [];
$table.children( "tr" ).each( function( y, row ) {
$( row ).children( "td, th" ).each( function( x, cell ) {
var $cell = $( cell ),
cspan = $cell.attr( "colspan" ) | 0,
rspan = $cell.attr( "rowspan" ) | 0,
tx, ty;
cspan = cspan ? cspan : 1;
rspan = rspan ? rspan : 1;
for( ; m[y] && m[y][x]; ++x ); //skip already occupied cells in current row
for( tx = x; tx < x + cspan; ++tx ) { //mark matrix elements occupied by current cell with true
for( ty = y; ty < y + rspan; ++ty ) {
if( !m[ty] ) { //fill missing rows
m[ty] = [];
}
m[ty][tx] = true;
}
}
var pos = { top: y, left: x };
$cell.data( "cellPos", pos );
} );
} );
};
/* plugin */
$.fn.cellPos = function( rescan ) {
var $cell = this.first(),
pos = $cell.data( "cellPos" );
if( !pos || rescan ) {
var $table = $cell.closest( "table, thead, tbody, tfoot" );
scanTable( $table );
}
pos = $cell.data( "cellPos" );
return pos;
}
})(jQuery);
appendMe();
function appendMe() {
$('table.test td').find("em").remove()
$('table.test td').removeAttr("realCellEq").append(function(){
return "<em> " + $(this).cellPos().left + "</em>"
}).attr("realCellEq", function() {
return $(this).cellPos().left
});
}
$(function () {
$.contextMenu({
selector: 'table.test td',
items: {
"addRowBelow": {
name: "Add Row Below",
callback: function (key, options) {
$(this).parents("tr").after("<tr class='freshAdd'></tr>");
$(this).parents("tr").find("td").each( function() {
var thisRowSpan = ($(this).attr("rowspan")) ? $(this).attr("rowspan") : 1;
if(thisRowSpan > 1) {
$(this).attr("rowspan", (parseInt($(this).attr("rowspan"),10)+1));
} else {
$(this).clone().appendTo("tr.freshAdd");
}
});
$("tr.freshAdd").find("td").html("");
$("tr.freshAdd").removeClass("freshAdd");
appendMe();
}
}
}
});
});
问题是我无法弄清楚我需要做什么来考虑行跨度。
这是一个 jsfiddle 来解释我的意思。