【问题标题】:counting divs inside div计算 div 内的 div
【发布时间】:2011-09-02 17:57:45
【问题描述】:

我已尝试此页面上的解决方案来计算父(类)div 中的 div。但不幸的是,我的结果总是显示现有子 div 的总数。 因为示例跟随两个 span 标签将输出 7。

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

    <!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>

【问题讨论】:

    标签: html count parent children


    【解决方案1】:

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

    问题是你自己的,而

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

    这会选择容器中的所有 .detail 元素以及所有带有 .box 的子元素。一共是7个。 您应该使用 each() 遍历 .detail 并计算 .box 子项的数量并修改对应的 countDiv。

    【讨论】:

      【解决方案2】:

      我不知道你为什么要计算具有相同类名的 div。当您使用$('.detail') 时,它将获取页面中所有具有类名“detail”的元素,因此您无法通过这种方式将具有相同名称的特定div 与其他div 一起计算。

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

      我认为可能是:

      $('#content-body .detail').each(function() { 
            var n = $(this).children('.box').length;
            $(this).append("<div>There are " + n + " divs inside parent box detail.</div>");
      });
      

      如果你想计算特定的 div,你应该提供不同的类名。

      【讨论】:

      • 它的工作。 ...所以真正缺少的是 $(this)?谢谢!
      • each() 方法用于访问$('content-body .detail')$(this) 的每个元素,用于获取我们正在访问它的一个元素。
      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多