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

JC *_*bbs 9 jquery

我试图在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>
Run Code Online (Sandbox Code Playgroud)

以下jQuery调用:

$("div a.action:visible:first-child").addClass("first");
Run Code Online (Sandbox Code Playgroud)

但它似乎永远找不到合适的元素......它找到第一个元素但不是第一个可见元素.我甚至尝试交换选择器顺序":first-child:visible"而不是":visible:first-child",这也不起作用.有任何想法吗?

Raf*_*ael 28

你的选择器

$("div a.action:visible:first-child").addClass("first");
Run Code Online (Sandbox Code Playgroud)

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

如果要获取第一个可见的A元素,则应使用.eq函数

$("div a.action:visible").eq(0).addClass("first");
Run Code Online (Sandbox Code Playgroud)

或者:第一个伪类

$("div a.action:visible:first").addClass("first");
Run Code Online (Sandbox Code Playgroud)