开发者

How can I avoid deleting a ul element with this code?

开发者 https://www.devze.com 2023-03-25 06:01 出处:网络
I have an infinite scrolling gallery that uses markup like this (transformed through CSS to appear horizontal):

I have an infinite scrolling gallery that uses markup like this (transformed through CSS to appear horizontal):

<div>
    <ul>
        <li><img id="placeHolder" class="photo" .../></li>
    </ul>
</div>

Now, I have some jQuery that populates the UL element with bullets (li) which themselves contain images.

Past a certain defined number of images the first image should be removed. This is what the following code is supposed to d开发者_如何学Pythono.

// Limit to max
if( $('.photo:visible').size() >= maxPhotos ){
        $(".photo:first").parent().remove(); // Remove li also removes img
}

However, it appears that it also removes the UL after a certain time.

Any suggestions on how I could avoid this?


var $photos = $('.photo:visible');
if( $photos.length >= maxPhotos ){
    $photos.first().parent('li').remove();
}
  • .parent() can take a selector
  • Don't select the .photo elements twice
  • Use .length instead of .size()


You could just check to make sure it's an <li> tag before removing.

// Limit to max
if( $('.photo:visible').size() >= maxPhotos && $(".photo:first").parent().tagName == 'li'){
        $(".photo:first").parent().remove(); // Remove li also removes img
}


Try this

if( $('.photo:visible').size() >= maxPhotos ){
        $(".photo:first").closest("li").remove(); // Remove li also removes img
}


This would ensure that it was an li tag

if( $('.photo:visible').size() >= maxPhotos ){
    $(".photo:first").closest('li').remove(); // Remove li also removes img
}
0

精彩评论

暂无评论...
验证码 换一张
取 消