将数字添加到表中的第一列

时间:2014-02-16 12:34:18

标签: jquery

我正在尝试将数字添加到第一个col

中的表中
var newCol = "<td></td>";
$('#target tbody tr').append(newCol);
$('#target tbody tr').each(function (idx) {
    $(this).children(":eq(0)").html(idx);
});

但我不确定为什么代码不起作用? http://jsfiddle.net/9RHH2/1/

1 个答案:

答案 0 :(得分:0)

目标已经是tbody,更改选择器并使用:

DEMO jsFiddle

var newCol = "<td class='rownum'></td>";
$('#target tr').each(function (i) {
    $(this).prepend($(newCol).text(i + 1))
});

或仅使用CSS:

table {
    counter-reset: rowNumber;
}

table tr {
    counter-increment: rowNumber;
}

table tr td:first-child::before {
    content: counter(rowNumber);
    min-width: 1em;
    margin-right: 0.5em;
}

DEMO CSS

相关问题