2011-03-18 53 views
2

我想基於每個相應列中第一個<td>的對齊來設置表頭的對齊。基於第一行對齊設置表頭對齊

<table> 
    <thead> 
     <tr> 
      <th>First Column</th> 
      <th>Second Column</th> 
      <th>Third Column</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>Value One</td> 
      <td align="right">Value Two</td> 
      <td align="center">Value Three</td> 
     </tr> 
     <!-- more rows --> 
    </tbody> 
</table> 

在這個例子中,第二<th>會得到一致的權利和第三<th>會得到居中。第一個<th>不會受到影響。任何建議/如何用jQuery來實現這一點的例子將非常感激。


基於InfernalBadger的回答,這是我最終使用的。原來我需要考慮CSS text-align屬性以及處理多個表。

function alignGridHeaders() { 
    $('table.grid thead th').each(function (index) { 
     var cell = $(this).parents('table:first').children('tbody tr:first td').eq(index); 
     var alignment = cell.css('text-align'); 
     if (!alignment) 
      alignment = cell.attr('align'); 
     if (alignment) 
      $(this).css('text-align', alignment); 
    }); 
} 

回答

2

JSFiddle Example

$('#myTable th').each(function(index) { 
    var alignment = $('#myTable tbody tr:first td').eq(index).attr('align'); 
    if (alignment) 
     $(this).css('text-align', alignment); 
}); 

我給表myTable的的ID對於這個例子。

0

您可能會想要使用jQuery eq函數。這將允許你簡單地傳入你想修改的元素的數量。在你的情況下,它可能看起來像這樣

$(document).ready(function(){ 

    $('#trID li').eq(2).css('align', 'right') 
    $('#trID li').eq(3).css('align', 'center') 

}); 

希望這會有所幫助!

1

另一種可能效率低得多的方法。它確實具有空白或不對齊指令的優點,但那並不多。

function toprowalign(){ 
    var pos = 1; 
    $('table tr:nth-child(1) ').children('td').each(function(){ 
     var align = $(this).attr('align'); 
     if(align==''){align='left';} 
     $('table tr th:nth-child('+pos+') ').attr('align',align); 
     pos++; 
    }) 
}