几乎有了 - 用动态数据描绘一个表格 - 这可以右对齐表格中的日期和数字列但更重要的是我还想右对齐相应 <thead><th>
中的标签列柱子。如果我了解幕后情况,下面的这个方法一次一行,如果有匹配,它适用 text-align:right
到 <td>
.因此,如果对表中找到正则表达式匹配的每个 tr 执行此操作,它将执行 text-align: right
到 <th>
如果我有 100 行,那么它不会尝试做 500 x,这太过分了。我如何更好地执行此操作以在正则表达式匹配上右对齐标签一次。
$('tr').each( function ()
{
// right align any numeric columns
$(this).children('td:gt(0)').filter(function()
{
return this.innerHTML.match(/^[0-9\s\.,]+$/);
}).css('text-align','right');
// right align any date columns in ddmmmyyyy format
$(this).children('td:gt(0)').filter(function()
{
return this.innerHTML.match(/\d{1,2}\w{3}\d{2,4}/);
}).css('text-align','right');
});
HTML:
<thead><tr><th>Name</th><th>Age</th></tr></thead>
<tbody>
<tr><td>Silly Me</td><td>29</td></tr>
<tr><td>Not again</td><td>48</td></tr>
....
</tbody>
因此它将遍历文档并在第 2 行看到一个数字列。所以我想要右对齐以及相应的列,但我们只对行执行一次。
有道理吗?
最佳答案
如果我理解得很好,如果标题“年龄”下方的任何单元格是数字(当然它们也会与您的 js 函数对齐),您希望标题“年龄”右对齐... 为此,我对您的代码做了一些小的修改,所以我们开始吧:
HTML(我在这里添加了更多行,以便您可以看到带有更多选项的示例):
<table>
<thead><tr><th>Name</th><th class="testclass">Age</th></tr></thead>
<tbody>
<tr><td>Silly Me</td><td>24</td></tr>
<tr><td>Not again</td><td>df</td></tr>
<tr><td>Once more</td><td>32</td></tr>
<tr><td>and again</td><td>test22</td></tr>
<tr><td>today is</td><td>13052014</td></tr>
<tr><td>and final</td><td>41</td></
tr>
</tbody>
</table>
CSS(这样做的唯一目的是扩大表格的宽度并添加一些边框,以便示例也能显示得更清楚!):
table {width:300px; border:1px solid #ddd;}
th,td {border:1px solid #ddd;}
JS(这里是我的修改,所以我把它留在最后!):
$('tr').each( function ()
{
// right align any numeric columns
$(this).children('td:gt(0)').filter(function()
{
var cond1 = this.innerHTML.match(/^[0-9\s\.,]+$/);
if (cond1){
$(this).css('text-align','right');
$(".testclass").css('text-align','right');
}
});
// right align any date columns in ddmmmyyyy format
$(this).children('td:gt(0)').filter(function()
{
var cond2 = this.innerHTML.match(/\d{1,2}\w{3}\d{2,4}/);
if (cond2){
$(this).css('text-align','right');
$(".testclass").css('text-align','right');
}
});
});
希望这就是您要找的,并且对您有所帮助。编码愉快!
(在此处查看它的工作情况:http://jsfiddle.net/Pxwg3/)
关于jquery - 右对齐表格中的数值和 <thead>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619790/