Sum of values from different divs with the same class

后端 未结 6 1788
囚心锁ツ
囚心锁ツ 2020-12-13 18:15

I am loading dynamically divs that have a .totalprice class. At the end, I would like to sum of the values from all of the .totalprice.

6条回答
  •  孤城傲影
    2020-12-13 18:37

    To build on what Rionmonster's did, this works for me:

    HTML:

    6.7
    8.9
    4.5

    JavaScript:

    var sum = 0;
    $('.totalprice').each(function()
    {
        sum += parseFloat($(this).text());
    });
    alert(sum);
    

    Output:

    21.1
    

    I find that in getting the value out of a

    you have to use the .text() selector. Here is the fiddle to see it work: http://jsfiddle.net/davecoulter/7D7nR/

提交回复
热议问题