0

我有一些输入字段,而不是我想要的数组,以便我可以在页面上的表格中查看它们。我已经能够使用.serializeArray()创建一个数组

这个小提琴中,我已经能够输出我的数组,但是我希望数据显示在我在小提琴底部硬编码的表格中,它将汤姆和杰瑞的所有实例分组到每个 id 的一行中. 累积该 ID 的所有销售值等。我想按总销售价格列对其进行排序。我知道执行此操作的服务器端技术,但是在这种情况下,我正在寻找 jquery 解决方案。实现这一目标的最佳方法是什么?

4

1 回答 1

1

我假设您可以依赖隐藏的输入字段,这些字段总是以四个一组的形式出现,每个组都有一个id[], name[], sales[]& price[],否则(显然)您无法分辨哪些字段是相关的。因此,不是使用.serializeArray()返回包含所有值的单个数组的 use ,而是将 id 放在它们自己的数组中,将名称放在它们自己的数组中,等等。也许是这样的:

function showValues() {
    function getVal(el, i) {
        return el.value;
    }
    var ids = $.map($('input[name="id[]"]'), getVal),
        names = $.map($('input[name="name[]"]'), getVal),
        sales = $.map($('input[name="sales[]"]'), getVal),
        prices = $.map($('input[name="price[]"]'), getVal),
        data = {},
        i,
        $results = $("#results");

    for (i = 0; i < ids.length; i++) {
        if (!data[ids[i]]) {
            // if current id is new add a record for it:
            data[ids[i]] = {
                "id":ids[i],"name":names[i],"sales":+sales[i],"price":+prices[i]
            };
        } else {
            // otherwise add to existing record's totals
            data[ids[i]].sales += +sales[i];
            data[ids[i]].price += +prices[i];
        }
    }
    // data object now contains the details for each salesman,
    // so turn it into an array to allow sorting:
    data = $.map(data, function(val, key) { return val; });
    data.sort(function(a,b) { return a.price - b.price; });

    // now output table - assume there's already a table element with headings
    $.each(data, function(i, val) {
        var $tr = $("<tr></tr>").attr("data-id", val.id).appendTo($results);
        $("<td></td>").text(val.name).appendTo($tr);
        $("<td></td>").text(val.sales).appendTo($tr);
        $("<td></td>").text(val.price).appendTo($tr);
        $("<td></td>").text(val.price / 10).appendTo($tr);
    });
}

工作演示:http: //jsfiddle.net/nnnnnn/VNSam/5/

作为解释,这一行:

ids = $.map($('input[name="id[]"]'), getVal)

...说用 获取所有输入name="id[]",并将生成的 jQuery 对象传递给该$.map()方法,以便我们可以取回一个仅包含 id 值的数组 - 您可以看到这getVal()只是一个简单的函数,可以做到这一点。我为name[]其他领域做同样的事情。

另请注意,当从输入中检索时,销售额和价格值是字符串,因此我使用一元加号运算符将它们转换为数字。

于 2012-08-05T03:06:37.433 回答