Count li elements that are visible with jQuery

2020-06-03 01:41发布

Im counting my li elements with the following jQuery script:

HTML:

<ul class="relatedelements">
   <li style="display:none;" class="1">anything</li>
   <li style="display:none;" class="2">anything</li>
   <li style="display:none;" class="3">anything</li>
</ul>

jQuery:

    $(function() {
        var numrelated=$('.relatedelements > li').length;
        $('.num-relatedelements').html(numrelated); 
    });

--> The script returns: 3

I change the style="display: none" property of some of the li elements when $(document).ready with jQuery, like: $('.2').show();

I now want to change the script in a way to count only the visible li elements with the following script (i just added :visible following the jQuery docs):

    $(function() {
        var numrelated=$('.relatedelements > li:visible').length;
        $('.num-relatedelements').html(numrelated); 
    });

--> The script returns: nothing

I have no clue why it doesn't work out - maybe anyone has any tip or idea? Any help is much appreaciated. Thanks upfront!

9条回答
别忘想泡老子
2楼-- · 2020-06-03 02:21

It works like that:

$(function() {
    var numrelated=$('.relatedelements > li:visible').length;
    $('.num-relatedelements').html(numrelated); 
});

You can see working example there.

查看更多
Melony?
3楼-- · 2020-06-03 02:28

I have tried this out and it seems to work i.e. I get a result of '1'.

$(function() {
    $('.2').show();

    var numrelated=$('.relatedelements > li:visible').length;
    $('.num-relatedelements').html(numrelated); 
});

NB: I don't think having numbers for the value of an attribute is valid markup

查看更多
啃猪蹄的小仙女
4楼-- · 2020-06-03 02:32

Yep, as everyone has already said, it works fine, even when you .show() the element doc ready:

http://jsfiddle.net/bKyt4/

查看更多
地球回转人心会变
5楼-- · 2020-06-03 02:33

Your script returns nothing because all DIV's are hidden. It returns 1 when 1 is shown.

查看更多
▲ chillily
6楼-- · 2020-06-03 02:34

work fine for me

$(document).ready(function(){
    $('.2').show();
    var numrelated=$('.relatedelements > li:visible').length;
    $('.num-relatedelements').html(numrelated); 
});​

JsFiddle Lind : http://jsfiddle.net/xuckF/1/

查看更多
别忘想泡老子
7楼-- · 2020-06-03 02:34

Works fine here:

http://jsfiddle.net/jtbowden/FrPPr/ (1 visible)

http://jsfiddle.net/jtbowden/FrPPr/1/ (0 visible)

Now, using numbers as class names is illegal. (W3C Spec, bullet 2) Class names must start with a letter. Maybe doing manipulations with that is causing problems?

Other than that, I can only guess your problem is elsewhere. Are you using the latest version of jQuery? (Although in my tests, it works all the way back to 1.3, and then it doesn't work at all)

Did you misspell "visible" in your actual code. (I've done this before)

查看更多
登录 后发表回答