使用jquery从具有嵌套表的表中选择顶级列

时间:2009-05-28 16:02:36

标签: jquery

我有以下html结构(生成并且我无法更改):

<table id='tableID'>
<tbody>
    <tr>
        <td>
            <table>...</table>
        </td>
        <td>
            <table>...</table>
        </td>
        <td>
            <table>...</table>
        </td>
    </tr>
    <tr>
        <td>
            <table>...</table>
        </td>
        <td>
            <table>...</table>
        </td>
        <td>
            <table>...</table>
        </td>
    </tr>
    ....
</tbody>
</table>

我要做的是获取所有外部行和外部行中的每列操作内容。所以我有类似的东西:

var rows = $("#tableID > tbody > tr");
$.each(rows, function(n, row)
{
     var columns = row.children("td");
     if (columns.length > 0) {
          $.each(columns, function (i, column)
          {
               //do stuff
          });
     }
});

我遇到的问题是,当我得到孩子的tds时,它太贪婪并且也从嵌套表中抓取tds。有谁知道我如何限制这个,以便我只从外表的当前行获取tds?或者有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

您可能不必要地循环两次。如果想要修改不属于嵌套表的每个单元格,这应该可行。

var cells = $("#tableID > tbody > tr > td");
$.each(cells, function(n, cell){     
   //do stuff          
});

答案 1 :(得分:3)

var rows = $("#tableID > tbody > tr");
rows.each(function(n, row)
{
     $(row).children().each( // td implicit, since tr should only contain td
        function (i, column) {
           //do stuff
           // Note, if you don't need a reference to row inside the function,
           // you can loop directly over the tds by adding > td to the first
           // selector and skip the outer loop.
        });
     }
});