简体   繁体   English

无法将项目推入空数组

[英]Can't push item into empty array

I have this function where when I click a button I loop over some divs and get the id of that div along with some checkbox inputs id's if they are marked. 我有这个功能,当我点击一个按钮时,我循环遍历一些div并获得该div的id以及一些复选框输入id如果它们被标记。 To store this values I have a dictionary which is suppose to store the items like this: 为了存储这个值,我有一个字典,假设存储这样的项目:

{
   1: [4,5],
   2: [2,3]
}

The keys represent the id's of each div and the values are the checkbox items id's that are clicked. 键表示每个div的id,值是单击的复选框项ID。

Full code: 完整代码:

$(document).on('click', '.trimite-rasp', function(){
    var formData = {}
    $.each($('.single-question'), function(){
        var listIds = [];
        var qId = $(this).attr('qid');
        console.log(qId);
        $.each($('.form-check-input'), function(){
            if($(this).is(':checked')){
                var thisId = ($(this).attr('aid'));
                $(listIds).push(thisId);
            }
        });

        formData[qId] = listIds;
    });
    console.log(formData);

});

The only problem here is that listIds array is always empty. 这里唯一的问题是listIds数组总是为空。 I can't push the values to that array, and I'm sure the checkbox id is correct because I console.log it and it's taken correctly. 我无法将值推送到该数组,并且我确定复选框ID是正确的,因为我是console.log它并且它被正确地使用了。

It is because you are using the array as a jQuery selector 这是因为您将数组用作jQuery选择器

use 采用

var thisId = $(this).attr('aid'); 
listIds.push(thisId);

instead of 代替

 $(listIds).push(thisId);

尝试这个

listIds.push(thisId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM