jQuery - 仅将某些值传递给运行总计

时间:2014-09-01 21:07:44

标签: javascript jquery

我有以下代码将20个值作为运行总计传递给变量total

total += parseInt($(this).html(),10);

我怎样才能达到同样的效果,但仅限于传递20的第5,第10和第15个值?

编辑:

$('#table1 .set2').each(function()
    {
        total += parseInt($(this).html(),10);
    });

1 个答案:

答案 0 :(得分:1)

我认为您的完整代码类似于:

$('#table1 .set2').each(function (idx) {
    total += parseInt($(this).html(),10);
});

您需要做的是使用mod运算符,如下所示:

$('#table1 .set2').each(function (idx) {
    if ((idx + 1) % 5 === 0 && idx !== 19)) {
        total += parseInt($(this).html(),10);
    }
});

除第20个以外的每5个值。请注意+ 119,因为它已归零。

使用任意值执行此操作的另一种方法是:

$('#table1 .set2').each(function (idx) {
    if ([4, 9, 14].indexOf(idx) !== -1) {//5th, 10th and 15th
        total += parseInt($(this).html(),10);
    }
});

编辑使代码更容易阅读。(使用if而不是三元运算符)