【问题标题】:How to select different cell from the same row in jQuery?如何从jQuery中的同一行中选择不同的单元格?
【发布时间】:2013-10-14 10:38:38
【问题描述】:

我有这个 jQuery 选择器:

'table tbody tr td:first-of-type'

如何从 $(this) 为同一行构造一个单元格选择器?我需要检查

 $(document).on('click','table tbody tr td:first-of-type',function()
 {
   if ( $('table tbody tr td:nth-child(2)').text() != "" ) // for the same row !!
   //do something
   else
   //do something else
 }

额外的问题:我应该避免使用像 nth-child() 这样的 CSS3 选择器并使用像 eq() 这样的 jquery 选择器吗?

【问题讨论】:

  • 您能发布一些 HTML 和您想要实现的示例吗?您的问题并不完全清楚。
  • 您在选择器中忘记了一些',是拼写错误吗?应该是if( $('table tbody tr td:nth-child(2)').text() != "" )
  • @Sergio 是的,只是错字

标签: jquery html-table jquery-selectors


【解决方案1】:

只要找到最近的tr

$(this).closest("tr")

要选择td,请使用链接到该.find()

$(this).closest("tr").find("td") //and whatever criteria you need

【讨论】:

  • 那你怎么选择你需要的td呢?
  • @GytisŠk -- 已编辑并添加到答案
  • 这是唯一的方法吗?看起来效率不高(一般情况下)
  • 如果您需要访问多个单元格,建议将“最近”的结果分配给变量。然后您可以使用该变量上的 find 来避免重新扫描并再次找到 TR。
【解决方案2】:

工作代码:

   <html>
        <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(e) {
        if ($('table tbody tr td:nth-child(2)').text() != "" ){ // for the same row
       //do something
        // alert($('table tbody tr td:nth-child(2)').text());
        }else{
       //do something else
       //alert("test");
        }

           });
        </script>

        </head>
        <body>
        <table>
        <tbody>
            <tr>
                <td>itemOne</td>
                <td>itemOneInfo</td>
                <td>Info</td>
            </tr>
            </tbody>
        </table>
        </body>
        </html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多