2016-09-15 74 views
0

我需要隐藏使用jQuery的HTML表格的一些列。我使用下面的代码:jQuery的nth子选择器问题

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

的代码工作,它的隐藏表的列,但不尊重表id选择,它采用当前文档中的所有表的变化。

我该如何改变才能使其按预期工作?

+7

'$('#我的表TR TD:第n个孩子(7),#我的表个:第n个孩子(7)')' - 你必须每次都声明外部ID,它不能猜到这就是你的意思 –

+0

上面的评论很可能是你的问题。你错过了第二个选择器上的ID – Huangism

+0

谢谢,它现在正在工作! @DarrenSweeney –

回答

2

你需要指定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() 
+0

谢谢!,这与Darren上面提供的答案是一样的。既然这是这个问题的第一个答案,我会在5分钟之内接受它是正确的。对不起,SO时间限制。 –

+0

难道不够:$('#my-table tr:nth-​​child(7)')。hide()'?!因为'tr'的孩子只能是'td'或'th'(或'template',但它不会显示) –

+0

@ A.Wolff是的,我会把它加到我的答案中,谢谢。 – dippas

1

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