我试图选择所有显示的最后一个元素:隐藏父元素中的块属性.
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,但解决方案适用于可见的父级.
最佳答案 试试这个:
$('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');
});
});