按类别划分的总数据属性值

时间:2015-01-18 19:06:25

标签: javascript jquery

我尝试使用jQuery从列表中按数据属性名称查找总金额组。类似于分组类别并找到总和。

例如,我想创建这样的东西:

group1 = 3
group2 = 5
group3 = 3

从此列表中:

<span class="data-center" data-category="group1" data-amount="1"></span>
<span class="data-center" data-category="group2" data-amount="1"></span>
<span class="data-center" data-category="group2" data-amount="2"></span>
<span class="data-center" data-category="group1" data-amount="2"></span>
<span class="data-center" data-category="group2" data-amount="2"></span>
<span class="data-center" data-category="group3" data-amount="3"></span>

我想知道是否有一些jQuery函数帮助实现它,比如groupByName()

2 个答案:

答案 0 :(得分:3)

使用纯JavaScript:

Example Here

function getCategoryTotal(cat) {
    var total = 0,
        elements = document.querySelectorAll('[data-category="' + cat + '"]');

    Array.prototype.forEach.call(elements, function (el, i) {
        total += parseInt(el.dataset.amount, 10);
    });

    return total;
}

console.log(getCategoryTotal('group1')); // 3
console.log(getCategoryTotal('group2')); // 5
console.log(getCategoryTotal('group3')); // 3

答案 1 :(得分:0)

我猜你问过jQuery这样做的方式,我做了:

$.fn.amountByData = function(dataAttr, amountDataAttr) {
    if (typeof amountDataAttr == "undefined")
        amountDataAttr = "amount";

    var dataAmountArr = new Array();

    $(this).each(function() {
        var dataAttrVal = $(this).data(dataAttr);

        if (typeof dataAmountArr[dataAttrVal] == "undefined")
            dataAmountArr[dataAttrVal] = parseInt($(this).data(amountDataAttr));
        else 
            dataAmountArr[dataAttrVal] += parseInt($(this).data(amountDataAttr));
    });

    return dataAmountArr;
};

在这里,我将如何实现jQuery方式!这提供了 LOT 的灵活性,因为您可以选择要根据哪个数据属性计算金额,并且如果未命名{{{},您还可以选择精确不同数量的数据属性。 1}}。

PS:我知道已经选择了一个答案,但与@Josh Crozier相反,我知道你想要一个jQuery方法来实现你的目标。

干杯,

相关问题