2013-10-16 48 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

相關問題