jQuery 第 n 个子选择器问题

jQuery nth-child selector issue

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

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

代码正在运行,它隐藏了 table 的列,但是没有考虑 table id 选择器,它正在对所有 table 应用更改当前文档。

我应该改变什么才能让它按预期工作?

您需要为两个选择器指定 id,否则 th:nth-child(7) 它将隐藏您可能拥有的 every 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()

您可以使用 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)')