Sum of values from different divs with the same class

后端 未结 6 1767
囚心锁ツ
囚心锁ツ 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:45

    If you do this very often throughout your code, it is recommended to put it in a nice reusable function

    function removeComma(x)
    {
       if (x) 
       {
           if (x.length > 0) 
           {
            return x.replace(/,/g,'');
           }
       }
    }
    function sum_class(list,source)
    {
        // source can be text for non input DOM elements or value for text inputs
        var total = 0;
        $(list).each(function() {
        if (source == 'text') 
        {
             total += parseFloat(removeComma($(this).text()));
        }
        else
        {
             total += parseFloat(removeComma($(this).val()));
            }
        }); 
        return total;
    }
    

    Keep in mind that both functions use variables I've name to what makes sense to me, you can rename them to what you understand works better for you, like the name of the function sum_class, is not referring to an OOP class but the the purpose of the function which is to return the total of values from elements that belong to the same class.

提交回复
热议问题