2011-03-18 55 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++; 
    }) 
}