如何使用jQuery引用表行

时间:2011-07-27 14:33:40

标签: javascript jquery html

下午,

我希望将表的行号传递给函数以引用该特定表中的特定行,例如说我有这个:

<table id="foo">
  <tr><td>some stuff...</td><tr>
  <tr><td>stuff</td><tr>
  <tr><td>more stuff</td><tr>
  <tr><td>some stuff</td><tr>
  <tr><td>some stuff</td><tr>
</table>

我循环遍历表行并获取了索引,所以在这个例子中说我想用第三行做一些事情(索引为2,内容为“more stuff”) 。我通过一个函数传递了这个,就像这个

manipulateRow(2)

这是我的全部功能

function manipulateRow(rowIndex){

/* do something */

}

如何将rowIndex参数引用到函数中的表中?例如:

$('#foo').child("tr")[rowIndex].html('<td>i now contain even more stuff!</td>'); // I know this is wrong, how do I make it right?

对不起,如果我有点厚或不解释自己。

5 个答案:

答案 0 :(得分:2)

易。

$("#foo tr:eq("+rowIndex+")").html("<td>i now contain even more stuff!</td>");

在此处了解有关jQuery选择器的更多信息:http://api.jquery.com/category/selectors/

答案 1 :(得分:0)

实际上只能这样工作:

$($('#foo tr')[rowIndex]).html('<td>i now contain even more stuff!</td>');

但最好使用:eq

答案 2 :(得分:0)

试试这个

$('#foo > tr').eq(rowIndex).html('<td>i now contain even more stuff!</td>');

答案 3 :(得分:0)

function manipulateRow(rowIndex) {
    var $row = $('#foo tr:nth-child(' + rowIndex + ')');
    ...
}

请参阅nth-child-selector

答案 4 :(得分:0)

你去:

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>

$("#myTable > tbody").append("<tr><td>row content</td></tr>");

继承人另一个内联编辑示例:

function editRow(row) {
    $('td',row).each(function() {
         $(this).html('<input type="text" value="' + $(this).html() + '" />');
    });
}