我试图在隐藏的父元素中选择每个最后获得display:block
属性的元素。
Here is an example fiddle to play with.
HTML:
<ul style="display:none;">
<li>1</li>
<li>2</li>
<li>3</li><!-- my goal is find last visible child on every hidden ul -->
<li style="display:none;">4</li>
</ul>
jQuery的:
$('ul').each(function() {
visibleCountOnEachUl =+ 0;
$(this).children('li').each(function(index) {
if ( $(this).css('display') === 'block' ) {
visibleCountOnEachUl += 1;
$(this).addClass('theseAreVisible');
//this part works;
//i can select elems elems which got display:block
//but can't select the last elem on each ul
//if ( index === (visibleCount-1) ) {
//$(this).addClass('last-visible');
//}
}
});
});
$('ul').find('li:visible:last').addClass('last-visible');
//This won't effect on child elements while their parent is hidden.
我发现这个类似question,但解决方案适用于可见父级。
答案 0 :(得分:3)
试试这个:
$('ul').each(function() {
$(this).children('li').each(function(index, elem) {
var l = $(elem).parent().find('li').filter(function() {
return $(this).css('display') === 'block';
}).length;
if (index == l-1)
$(this).addClass('last-visible');
});
});
答案 1 :(得分:-1)
当父级显示时,这将起作用:block:
$('ul li:visible:last').addClass('select');
当父级显示为:none时,您应该将元素设置为绝对,可见性:隐藏或将它们放置在视口之外。
if( $('ul').css('display','none') ){
$('ul').css({
'display':'block',
'position': 'absolute',
'visibility': 'hidden'});
$('ul li:visible:last').addClass('select');
}