【问题标题】:Using the jQuery each function to count divs with the same class使用jQuery的每个函数来计算具有相同类的div
【发布时间】:2020-02-11 20:07:49
【问题描述】:

我为8个div创建了一个css类,我需要使用jquery的each函数来统计div并将结果显示在页面的html中,例如:“8个div出现”。

我创建了一个代码,但它不起作用,它没有显示结果。

代码:

 <script>
    $( ".class" ).each(function( index ) {
      console.log( index + ": " + $( this ).text() );
    });
    </script>

【问题讨论】:

  • 您能否发布您的控制台日志输出。不能在这里完成。所以你在这方面帮助我们。您的 html 也可能会有所帮助。
  • 这里是控制台日志输出的图像。 [1]:i.stack.imgur.com/JM8zP.png

标签: javascript jquery html css magento


【解决方案1】:

如果你只想计算它们,你可以这样做: $('.class').length

【讨论】:

  • 我为这些 div 创建了一个特定的类,我希望我的代码按 css 类计数,我被锁定了。 :(
  • $('.class').length + ' divs appear'
【解决方案2】:

each() 方法获取相同的类 div index + content 或者您想计算有多少 div 具有相同的类,然后只需使用 .length

注意:检查 Full page. 然后您可以看到相同的类 div count result

// Console inded with each div text.
$('.sameclass').each(function(index){
  console.log(index +':'+ $(this).text());
});

//Count How many divs has (sameclass) class. 
$('.result').text($('.sameclass').length);
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<div class="sameclass">Text #1</div>
<div class="sameclass">Text #2</div>
<div class="sameclass">Text #3</div>
<div class="sameclass">Text #4</div>
<div class="sameclass">Text #5</div>
<div class="sameclass">Text #6</div>
<div class="sameclass">Text #7</div>
<div class="sameclass">Text #8</div>
<hr>
<p>Total divs has (sameclass): <strong class="result"></strong></p>

【讨论】:

    【解决方案3】:

    经过几次尝试,我设法解决了这个问题。

    我创建了三个代码,它们都起作用并给了我想要的结果。非常感谢您的帮助。

    1.

        var totalPageProducts;
    jQuery('.products-grid .item').each(function(index, value) {
    totalPageProducts = index + 1;
    jQuery('.show-no').html('Showing '+ totalPageProducts +' products');
    });
    

    2.

    jQuery(document).ready(function($) {
        jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
    });
    

    3.

    jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 1970-01-01
      • 2011-01-02
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 2023-03-25
      相关资源
      最近更新 更多