1

当您想处理一些累积结果时,如何循环遍历 jQuery 中的 children() 或 each() 调用的结果?例如,总结复选框中的数字,如果它们超过 100%,则更改一个类。所有示例似乎只执行每次迭代独立的逻辑。

我正在寻找这个 c# 的 javascript/jquery equiv

var x = new List<int> { 1, 2, 3 };
Console.WriteLine(x.All(y => y > 0));

这就是我现在所拥有的,但似乎应该有一些更清洁的东西。

var count = 0;
$(this).parent().children().each(
    function () {
        if ($(this).hasClass("selected")) {
            count++;
        }
    }
);

if ($(this).parent().children().length == count) {
    $(this).parent().parent().toggleClass("selected");
}
else {
    $(this).parent().parent().removeClass("selected");
}
4

4 回答 4

3

好吧,Javascript/Jquery 不是 SQL,没有定义“累积”/分组操作的概念。此外,“累积逻辑”是一个相当模糊的术语,它实际上取决于您要执行的特定任务。

因此,您的 sum 示例可以在each()外部变量的帮助下进行调整,对于input/text 标签,它将是:

var sum = 0;
var objects = $("input.myclass");
objects.each(function() {sum+=Number($(this).val());});
if (sum>100) objects.addClass("anotherclass");

对于复选框:我不确定您所说的“复选框中的总和”是什么意思,您是指值吗?

于 2012-08-14T00:57:10.503 回答
2

Aside from the obvious iterate and sum approach, you can use the newer javascript iteration functions. Assuming you want so sum some numbers:

var sum = objects
    //convert to jquery selection of numbers
    .map(function() {return +$(this).val(); })
    //convert to javascript array
    .get() 
    //add together
    .reduce(function(a, b) { return a + b; });

For your example:

var checkboxes = $(this).parent().children()
var allSelected = checkboxes.map(function () {
    return $(this).hasClass("selected");
}).get().every(function(x) { return x; });

You can go one stage better by extending jQuery

$.fn.every = function(f) {
    return [].every.call(this, function(x) {
        return f.call(x);
    });
}

Leaving you with:

var checkboxes = $(this).parent().children()
var allSelected = checkboxes.every(function() {
    return $(this).hasClass("selected");
});
于 2012-08-14T01:02:40.640 回答
1

Unlike the linear array operations map and filter, jQuery doesn't have a polyfill for it, but I think what you're looking for is Array.reduce. It is well-supported in newer browsers.

You can implement the javascript you have there using the boolean toggleClass syntax.

var count = $(this).parent().children(".selected").length;
$(this).parent().parent().toggleClass("selected",
    $(this).parent().children().length === count);
于 2012-08-14T01:01:18.390 回答
0

It's not that hard. I'm not sure if this will work 100%, but it'll show you how to do cumulative logic

var score = 0;
$("#checkboxDivId input[type=checkbox]:checked").each(function()
{
    score += $(this).val();
});
if(score >= 100)
{
    //Put your code here
}

Obviously this would only work if your score is the value property of the checkbox, and if the selector is correct (not 100% sure on whether or not the selector is correct)

于 2012-08-14T01:00:37.657 回答