在 jQuery 中一起使用 :visible 和 :first-child

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/830569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:52:58  来源:igfitidea点击:

Using :visible and :first-child together in jQuery

jquery

提问by JC Grubbs

I'm trying to use the ":visible" and ":first-child" pseudo-selectors together in jQuery and it doesn't seem to be working out. I have the following HTML:

我试图在 jQuery 中一起使用 ":visible" 和 ":first-child" 伪选择器,但它似乎没有奏效。我有以下 HTML:

<div>
    <a class="action" style="display:none;">Item One</a>
    <a class="action">Item One</a>
    <a class="action">Item One</a>
</div>

And the following jQuery call:

以及以下 jQuery 调用:

$("div a.action:visible:first-child").addClass("first");

But it never seems to find the right element...it finds the first element but not the first visibleelement. I've even tried swapping the selector order ":first-child:visible" instead of ":visible:first-child" and that doesn't work either. Any ideas?

但它似乎从未找到正确的元素……它找到了第一个元素,但没有找到第一个可见元素。我什至尝试过交换选择器顺序 ":first-child:visible" 而不是 ":visible:first-child",但这也不起作用。有任何想法吗?

回答by Rafael

Your selector

您的选择器

$("div a.action:visible:first-child").addClass("first");

matches only the Aelement only when it's the first-child of the parent DIV and when it is visible.

仅当A元素是父 DIV 的第一个子元素且可见时,才匹配A元素。

If you want to get the first visible Aelement, you should use the .eq function

如果你想获得第一个可见的A元素,你应该使用.eq 函数

$("div a.action:visible").eq(0).addClass("first");

or the :first pseudo-class

:first 伪类

$("div a.action:visible:first").addClass("first");

回答by Kobi

I'm not sure why :visible:first-childisn't working, but you can try

我不确定为什么:visible:first-child不起作用,但你可以试试

$("div a.action:visible").eq(0).addClass("first");

回答by PatrikAkerstrand

As far as I know the pseudo-class selector :first-child will only match the first child ever. It can not be further specified by adding a pseudo-class that it must also be visible. You might want to try writing

据我所知,伪类选择器 :first-child 只会匹配第一个孩子。不能通过添加伪类来进一步指定它也必须是可见的。你可能想尝试写作

$("div a.action:visible:first").addClass("first");

instead of using the proper css pseudo-class. JQuery documentation for :first

而不是使用正确的 css 伪类。用于 :first 的 JQuery 文档

回答by Ryan Rohrer

You might want to try $( "div a.action:visible(:first-child))as your selector, that is how jQuery specifies using multiple psuedo-selectors in its API documentation.

您可能想尝试$( "div a.action:visible(:first-child))作为您的选择器,这就是 jQuery 在其 API 文档中指定使用多个伪选择器的方式。