Sum using jQuery each function without global variable

后端 未结 5 791
执念已碎
执念已碎 2021-01-14 03:47

I want to add some HTML elements that have the same class name.

So, the code will be like this with jQuery.

$(\".force\").each(function (){
    a +=          


        
5条回答
  •  梦谈多话
    2021-01-14 04:40

    For convenience, if you're going to be needing this same functionality frequently, I'd probably just make a plugin.

    Example: https://jsfiddle.net/tzw4mkL2/

    (function( $ ) {
        $.fn.sumHTML = function() {
           var sum = 0;
            this.each(function() {
               var num = parseInt( $(this).html(), 10 );
               sum += (num || 0);
            });
           return sum; 
        };
    })( jQuery );
    

    ...which would be used like this:

    $('#total_forces').html( $('.force').sumHTML() );
    

    EDIT: Changed to guard agains NaN as noted by @Šime Vidas. Also ensured base-10 in the parseInt() and fixed a closing } that was missing.

提交回复
热议问题