需要帮助构建这个jQuery

bra*_*boy 3 html javascript jquery

我的html页面中有一堆div标签.现在我需要编写一个jQuery来计算网格的值.在下面的例子中,我将使用grid0作为基本id,我希望该系列中的计数为1.

<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>
Run Code Online (Sandbox Code Playgroud)

在下面给出的另一个例子中,我将使用从grid1开始的id,总值为6.请指导我!

<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>
Run Code Online (Sandbox Code Playgroud)

我试过这个jQuery("div[id^='grid0']").但这给了我所有的元素.但我需要使用其中的值进行计数.

谢谢!

hun*_*ter 6

首先选择带有starts-with选择器的div,然后遍历结果并计算输出为整数的文本值.


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");
Run Code Online (Sandbox Code Playgroud)

或者如果你想进一步使用jQuery函数:

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

然后你可以写:

var grid0Total = jQuery.gridSum("grid0");
var grid1Total = jQuery.gridSum("grid1");
Run Code Online (Sandbox Code Playgroud)

你也可以像这样使用map()函数:

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

在这里看到它们的全部内容:http://jsfiddle.net/FpmFW/1/

  • 哇,你的速度更快.仍然,有趣的是使用^ =选择器的东西:) (2认同)