【问题标题】:How do I reference a table row using jQuery如何使用 jQuery 引用表格行
【发布时间】:2011-10-14 08:10:39
【问题描述】:

下午,

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

<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,它的内容是“更多的东西”) .我通过一个函数传递了它,就像这样

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?

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

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    实际上只能这样工作:

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

    但最好使用 :eq

    【讨论】:

      【解决方案2】:

      简单。

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

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

      【讨论】:

      • 正是我想要的!非常感谢!
      【解决方案3】:

      试试这个

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

      【讨论】:

        【解决方案4】:
        function manipulateRow(rowIndex) {
            var $row = $('#foo tr:nth-child(' + rowIndex + ')');
            ...
        }
        

        nth-child-selector

        【讨论】:

          【解决方案5】:

          给你:

          <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() + '" />');
              });
          }
          

          【讨论】:

            猜你喜欢
            • 2013-01-03
            • 1970-01-01
            • 2017-07-30
            • 1970-01-01
            • 2020-11-08
            • 2010-12-28
            • 2021-08-23
            • 2011-02-13
            • 2018-05-30
            相关资源
            最近更新 更多