使用 jQuery 获取第一个可见元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18162689/
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
Getting first visible element with jQuery
提问by Yarin
Trying to get the first visible element of a list using jQuery's :first
and :visible
pseudo-selectors, as suggested here: https://stackoverflow.com/a/830611/165673but it's not working:
尝试使用 jQuery:first
和:visible
伪选择器获取列表的第一个可见元素,如下所示:https: //stackoverflow.com/a/830611/165673但它不起作用:
Fiddle:http://jsfiddle.net/FAY9q/4/
小提琴:http : //jsfiddle.net/FAY9q/4/
HTML:
HTML:
<ul>
<li>Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
<ul>
<li style="display:none;">Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
JQUERY:
查询:
$('li:visible:first').css('background','blue');
The first item in each list should turn blue...
每个列表中的第一项应该变成蓝色...
回答by Joe
Try using this:
尝试使用这个:
$('ul').find('li:visible:first').css('background','blue');
Currently your code is just getting the first visible li
element on the page and setting the background colour. This code selects all ul
elements then finds the first visible li
within each of them and applies the style.
目前您的代码只是获取li
页面上的第一个可见元素并设置背景颜色。此代码选择所有ul
元素,然后li
在每个元素中找到第一个可见的元素并应用样式。
Here it is working: http://jsfiddle.net/FAY9q/5/
它正在工作:http: //jsfiddle.net/FAY9q/5/
回答by user3353523
What about using this:
使用这个怎么样:
li:visible:not(:visible ~ :visible)
回答by Pranay Bhardwaj
$('li:visible').eq(0).css('background','blue');