将结果存储为新数组

时间:2017-10-08 11:38:34

标签: jquery each

我正在构建一个包含多个屏幕的调查问卷(仅按<section>拆分),并且需要将每个屏幕复选框结果存储为要在查询中使用的数组。

我认为使用.each()和动态分配的变量名称可以完成这项工作,但我的代码不会按部分拆分数组。

任何想法如何做到这一点?

$('.product_selector .submit').click(function(){
    i = 1;
    $('.product_selector section').each(function(){
        section[i] = $("ul li input:checkbox:checked").map(function () {
            return $(this).attr('name');
        }).get();
        i++;
    });
});

Codepen: https://codepen.io/chops07876/pen/xXWVVy

1 个答案:

答案 0 :(得分:1)

我认为您可能需要像这样编写代码。

$('.product_selector .submit').click(function () {
var result = []; // a variable to store the data.
$('.product_selector section').each(function(){
    // a variable to have each attribute.
    // the variable will have at least a blank array if none of the options are checked. In your previous code, if a section has no checkbox checked, then there wont be data for that section.
    var res = [];
    $(this).find("ul li input:checkbox:checked").each(function () {
        res.push(this.getAttribute('name'));
    });
    result.push(res);
});
console.log(result);});

我认为评论可能是解释性的。

相关问题