计算div内的div [英] counting divs inside div

查看:89
本文介绍了计算div内的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过此页面上用于解决父级(类)div中的div的解决方案。但不幸的是,我的结果总是显示现有子div的总数。
作为示例,同时跟随两个span标签将输出7。

i have tried the solutions on this page for counting divs inside parent (class) div. but unfortunately my result is alway displaying the whole number of existing children divs. as the sample follows both of the span tags will output 7.

为了更好地理解,这是html代码:缺少什么? -(我绝对是新角)。
thnx。

for better undersanding this is the code html: what is missing? - (i am absolutely greenhorn). thnx.

    <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>count</title>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="content-body" class="clearfix">

        <!-- detail div no 1 = 3 items inside -->
            <span class="countDiv"></span> 
            <div class="detail">
                <div class="box">
                    Div item 1
                </div>
                <div class="box">
                    Div item 2
                </div>
                <div class="box">
                    Div item 3
                </div>
            </div>
            <br /><br />
            <!-- detail div no 1 = 4 items inside -->
            <span class="countDiv"></span> 
            <div class="detail">
                <div class="box">
                    Div item 1
                </div>
                <div class="box">
                    Div item 2
                </div>
                <div class="box">
                    Div item 3
                </div>
                <div class="box">
                    Div item 4
                </div>
            </div>

        </div>
    <script type="text/javascript">

        $('#content-body').each(function() { 
            var n = $('.detail').children('.box').length;
            $(".countDiv").text("There are " + n + " divs inside parent box detail.");
        });

    </script>
    </body>
</html>


推荐答案

检查此小提琴: http://jsfiddle.net/geko/vXcgZ/

问题是

$('。detail')。children('。box')。length

这将选择容器中的所有.detail元素以及所有带有.box的子级。这总共是7。
您应该使用each()浏览.detail并为.box子代计数并修改coresponding countDiv。

This selects all .detail elements in your container and all children with .box. Which is a total of 7. You should go through .detail using each() and take count for .box children and modify coresponding countDiv.

这篇关于计算div内的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆