【问题标题】:jQuery nth-child selector issuejQuery nth-child 选择器问题
【发布时间】:2017-01-23 18:47:17
【问题描述】:

我需要使用 jQuery 隐藏 html 表的一些列。我正在使用以下代码:

$('#my-table tr td:nth-child(7),th:nth-child(7)').hide()

代码正在运行,它隐藏了表格的列,但是不尊重表格 ID 选择器,它正在为当前文档中的所有表格应用更改。

为了让它按预期工作,我应该改变什么?

【问题讨论】:

  • $('#my-table tr td:nth-child(7), #my-table th:nth-child(7)') - 每次都要声明外层ID,猜不出来就是这个意思
  • 上面的评论很可能是您的问题。您错过了第二个选择器上的 ID
  • 谢谢,现在可以使用了! @DarrenSweeney

标签: jquery jquery-selectors css-selectors


【解决方案1】:

您需要为两个选择器指定id,否则th:nth-child(7) 将隐藏每个您可能在代码中拥有的th:nth-child(7)

$('#my-table tr td:nth-child(7), #my-table th:nth-child(7)').hide()

您还可以使用find() 方法来简化此操作

$('#my-table tr').find('td:nth-child(7), th:nth-child(7)').hide()

编辑

正如@A. Wolff 所指出的,这可以更加简化:

$('#my-table tr > :nth-child(7)').hide()

【讨论】:

  • 谢谢!这与 Darren 在上面提供的答案相同。由于这是该问题的第一个答案,我将在 5 分钟内接受它为正确的。对不起,时间限制。
  • 这还不够吗:$('#my-table tr :nth-child(7)').hide()?!因为tr 的子级只能是tdth(或template 但无论如何都不会显示)
  • @A.Wolff 是的,我会把它添加到我的答案中谢谢。
  • 我编辑添加了子选择器以使其更加健壮,因为我们不知道可以包含什么 td :)
  • @A.Wolff 说得通:)
【解决方案2】:

您可以使用comma separated multiple selectors,但它应该是完整的选择器。

$('#my-table tr td:nth-child(7),#my-table th:nth-child(7)')

find() 具有多个内部元素选择器的方法

$('#my-table tr').find('td:nth-child(7),th:nth-child(7)')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多