问题
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