javascript长度返回3,应该有8

Yaa*_*pan -1 javascript jquery

我正在使用jQuery动态填写我在博客上发布的帖子数量.我.length用来获得帖子的数量.应该有八个帖子,但它会返回一个.
JS:

var nPosts = $(".l li ul").length; 
console.log(nPosts);
Run Code Online (Sandbox Code Playgroud)

HTML:

<ul class="l">
    <li style="list-style:none;">
        <h4>August 2015</h4>
        <ul class="list-group">
            <li class="list-group-item"><a href="blog/2015/08/difference-between-jquery-ui-and-bootstrap-icon" class="download" data-icon="download">The Difference between jQuery UI Icons and Bootstrap Glyphicons</a> - August 27</li>
            <li class="list-group-item"><a href="blog/2015/08/an-interesting-claim">An Interesting Claim</a> - August 28</li>
        </ul>
    </li>
    <br>
    <li style="list-style:none">
        <h4>September 2015</h4>
        <ul class="list-group">
            <li class="list-group-item"><a href="blog/2015/09/file-and-dir-same-name">How To Have a File and Directory with the Same Name</a> - September 1</li>
            <li class="list-group-item"><a href="blog/2015/09/comparing-apples-and-windows">Comparing Apples and Windows</a> - September 4</li>
            <li class="list-group-item"><a href="blog/2015/09/remove-space-from-list-item">How to Remove the Extra Space from a List Item</a> - September 6</li>
            <li class="list-group-item"><a href="blog/2015/09/how-long-will-the-new-ip-address-last">How Long will the New IP Address Last?</a> - September 8</li>
            <li class="list-group-item"><a href="blog/2015/09/how-to-loop-a-youtube-video">How to Loop a Youtube Video (The Easy Way)</a> - September 20</li>
        </ul>
    </li>
    <li style="list-style:none">
        <h4>October 2015</h4>
        <ul class="list-group">
            <li class="list-group-item"><a href="blog/2015/10/how-to-easily-download-anything">Two Ways to Easily Download Anything</a>
            </li>
        </ul>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Fil*_*ker 6

您正在查询LI elemts内部的UL,事实上,您有3个.

尝试

var nPosts = $(".l .list-group li").length; 
console.log(nPosts);
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好

var nPosts = $('.l .list-group-item').length;
Run Code Online (Sandbox Code Playgroud)

总是避免在一般用例中查询标记名,总是要查询id中的类(同样,在一般用例中).这样您就拥有了更多可控和可重用的逻辑.

$('#your-ID .your-classes')
Run Code Online (Sandbox Code Playgroud)