Need help creating this jQuery

I have a bunch of div tags in my html page. Now I need to write jQuery to calculate the grid value. In the example below, I will use grid0 as the base id, and I want the number in this series to be 1 here.

<div id="grid00">0</div>
<div id="grid01">0</div>
<div id="grid02">0</div>
<div id="grid03">1</div>
<div id="grid04">0</div>
<div id="grid05">0</div>

In the following example below, I will use an identifier starting with grid1, and the total value is 6. Please guide me!

<div id="grid10">5</div>
<div id="grid11">0</div>
<div id="grid12">0</div>
<div id="grid13">1</div>
<div id="grid14">0</div>
<div id="grid15">0</div>

I have tried this jQuery("div[id^='grid0']"). But it gives me all the elements. But I need an account using the value inside them.

Thank!

+3
source share
4 answers

divs starts-with , .


function GetSum(prefix) {
    var sum = 0;
    $("div[id^='" + prefix + "']").each(function(){
        sum += parseInt($(this).text());
    });
    return sum;
}

var grid0Total = GetSum("grid0");
var grid1Total = GetSum("grid1");

, jQuery:

jQuery.extend({
    gridSum: function(prefix) { 
        var sum = 0;
        if(!!prefix) { 
            $("div[id^='" + prefix + "']").each(function(){
                sum += parseInt($(this).text());
            });
        }
        return sum;
    }
});

:

var grid0Total = jQuery.gridSum("grid0");
var grid1Total = jQuery.gridSum("grid1");

map() :

var sum = 0;
$("div[id^='" + prefix + "']").map(function(){
    return sum += parseInt($(this).text());
});
return sum;

: http://jsfiddle.net/FpmFW/1/

+6

Try:

function total(idPrefix) {
    var total = 0;
    $('div[id^="' + idPrefix + '"]').each(function() {
        total += parseInt($(this).text());
    });
    return total;
}

var grid0total = total('grid0'),
    grid1total = total('grid1');

: http://jsfiddle.net/Au8Fr/

+4

divs commmon. - :

<div class="grid" id="myGrids">
<div class="grid" id="grid10">5</div>
<div class="grid" id="grid11">0</div>
<div class="grid" id="grid12">0</div>
<div class="grid" id="grid13">1</div>
<div class="grid" id="grid14">0</div>
<div class="grid" id="grid15">0</div>
</div>

:

var count=0;
$(".grid").each(function(){
 count+=parseInt($(this).text())
})
+1

grid0X divs :

var countOnes = 0;
$('div[id^=grid0]').each(function() {
    if ($(this).text() === "1") {
        ++countOnes;
    }
});

div, grid0 (, grid00, grid01 ..). , "1", , ; , .

Similarly, for grid1Xjust change the selector to use 1instead 0.

Alternatively, however, if these divs are in some kind of container, you can use the selector to find the container and then skip its children, for example:

HTML:

<div id="grid0">
    <div>0</div>
    <div>0</div>
    <div>0</div>
    <div>1</div>
    <div>0</div>
    <div>0</div>
</div>

JavaScript:

$("#grid0 > div").each(...);

... and avoid having all of these identifiers.

0
source

Source: https://habr.com/ru/post/1782780/


All Articles