Getting first visible element with jQuery

我怕爱的太早我们不能终老 提交于 2019-12-18 18:47:23

问题


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/165673 but it's not working:

Fiddle: http://jsfiddle.net/FAY9q/4/

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...


回答1:


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.

Here it is working: http://jsfiddle.net/FAY9q/5/




回答2:


What about using this:

li:visible:not(:visible ~ :visible)



回答3:


$('li:visible').eq(0).css('background','blue');


来源:https://stackoverflow.com/questions/18162689/getting-first-visible-element-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!