jQuery 来自同一个类的不同 div 的值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7249757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:36:01  来源:igfitidea点击:

Sum of values from different divs with the same class

jquery

提问by bobek

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

我正在加载具有.totalprice类的动态 div 。最后,我想将所有.totalprice.

回答by Rion Williams

For <div>Elements:

对于<div>元素:

var sum = 0;
$('.totalprice').each(function(){
    sum += parseFloat($(this).text());  // Or this.innerHTML, this.innerText
});

You can see a working example of this here

你可以在这里看到一个 工作示例

For <input>Elements (inputs, checkboxes, etc.):

对于<input>元素(输入、复选框等):

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

Alternatively, if you are looking for an integer, you can use the parseInt()function.

或者,如果您要查找整数,则可以使用该parseInt()函数。

You can see a working example of this here.

你可以在这里看到一个工作示例

回答by Rick

Unless you're absolutely certain about the value of your content, you will not be able to use parseFloatout of the box.

除非您绝对确定您的内容的价值,否则您将无法parseFloat开箱即用。

You need to be sure to handle:

您需要确保处理:

  • Excessive Whitespace
  • Leading $
  • Blanks
  • Unexpected Strings
  • 过多的空白
  • 领先$
  • 空白
  • 意外的字符串

Take a look:

看一看:

<div class="totalprice">  .25 </div>
<div class="totalprice">0.25     </div>
<div class="totalprice">.00 </div>
<div class="totalprice">  2.50</div>
<div class="totalprice">
var sum = 0;

$(".totalprice").each(function() {
    var val = $.trim( $(this).text() );

    if ( val ) {
        val = parseFloat( val.replace( /^$/, "" ) );

        sum += !isNaN( val ) ? val : 0;
    }
});

console.log( sum );
.01</div> <div class="totalprice"> </div>

The following will handle all cases:

以下将处理所有情况:

<div class="totalprice">6.7</div>
<div class="totalprice">8.9</div>
<div class="totalprice">4.5</div>

See also: http://jsfiddle.net/rwaldron/hfA5V/

另见:http: //jsfiddle.net/rwaldron/hfA5V/

回答by davecoulter

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

以 Rionmonster 所做的为基础,这对我有用:

HTML:

HTML:

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

JavaScript:

JavaScript:

21.1

Output:

输出:

(function( $ ){
   $.fn.sum=function () {
    var sum=0;
        $(this).each(function(index, element){
            if($(element).val()!="")
            sum += parseFloat($(element).val());
        });
    return sum;
    }; 
})( jQuery );
alert($('.abcd').sum());

I find that in getting the value out of a <div>you have to use the .text()selector. Here is the fiddle to see it work: http://jsfiddle.net/davecoulter/7D7nR/

我发现要从 a 中获取值,<div>您必须使用.text()选择器。这是查看它工作的小提琴:http: //jsfiddle.net/davecoulter/7D7nR/

回答by Karthik Vaithiyanathan

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='abcd' value='1'>
<input type='text' class='abcd' value='5'>
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;
}

More JQUERY Codes

更多 JQUERY 代码

回答by Darwin Santos Arismendy

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

如果你在整个代码中经常这样做,建议把它放在一个很好的可重用函数中

##代码##

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.

请记住,这两个函数都使用我命名为对我有意义的变量,您可以将它们重命名为您理解的更适合您的名称,例如函数 sum_class 的名称,不是指 OOP 类,而是函数的目的是返回属于同一类的元素的总和。