2013-10-16 50 views
1

可能还有其他类似的帖子,但这里什么都不做。为每个表格列添加colgroup

我目前正在对现有网站进行修改,并且所需的一些更改涉及列和行突出显示,如(tutorial/demo)。

由于有几个网页需要通过,我想有一些快捷方式来动态添加<colgroup></colgroup>,就像在这个例子中一样,不需要手工浏览每一页和table

我认为phppreg_replace功能,但我怀疑这是最简单的方法来解决它。在最佳情况下,我将能够验证每列是否存在现有的<colgroup></colgroup>阵列。

回答

2

使用jQuery,您可以在突出显示脚本之前动态地将<colgroup></colgroup>添加到每个表格。喜欢的东西 -

if($("table > colgroup").length == 0){ // If the table does not have <colgroup></colgroup> 

    var colCount = 0; 
    $('tr:nth-child(1) td').each(function() { // Get the count of table columns 
     if ($(this).attr('colspan')) { // if there is a <td colspan> 
      colCount += +$(this).attr('colspan'); 
     } else { 
      colCount++; 
     } 
    }); 


    var colgroupList = ''; 
    for (i=0;i<colCount;i++){ // Add a <colgroup></colgroup> for each <td> 
     colgroupList += '<colgroup></colgroup>'; 
    } 


    $("table").prepend(colgroupList); 

} 

$("table").delegate('td','mouseover mouseleave', function(e) { 
... 

的jsfiddle例如http://jsfiddle.net/BGR22/1/


编辑
如果你有一个页面上的多个表,你需要添加一个选择器仅获取父表 -

var $table = $(this).closest("table"); 

所以现在你的$("table").delegate()看起来像

$("table").delegate('td','mouseover mouseleave', function(e) { 
    var $table = $(this).closest("table"); 
    if (e.type == 'mouseover') { 
    $(this).parent().addClass("hover"); 
    $table.children("colgroup").eq($(this).index()).addClass("hover"); 
    } else { 
    $(this).parent().removeClass("hover"); 
    $table.children("colgroup").eq($(this).index()).removeClass("hover"); 
    } 
}); 

更新的jsfiddle - http://jsfiddle.net/BGR22/3/
,并与3个表 - http://jsfiddle.net/BGR22/4/

+0

这是很整齐!但是,在具有多个表格的页面上尝试此操作后,悬停会针对每列进行操作。见http://jsfiddle.net/BGR22/2/ – davewoodhall

+1

我已经更新了一个选择器,只有当前的表,更新jsFiddle。 – Sean

相关问题