使用从元素 id 的变量构建的数组分离和附加复选框选择

Detach and append on checkbox selection, using array built from variables of element ids

分离工作正常但不追加。我认为数组构建正确,但再次追加时,数组未定义。此外,如果多次未选中,我将需要避免将相同的元素添加到数组中。

JSFiddle:https://jsfiddle.net/ud2opLxx/4/

$(document).ready(function(){
var restoreMe = [];
 $("#studentCourses :checkbox").change(function() {

    var courseid = $(this).attr('id'),
        row = $(this).closest('tr'),
        cell = row.children('td').eq(3),
        course = cell.find('input');

    if($(this).prop("checked")) {
        //var rm = $.grep(restoreMe, function(e){ return e.courseid.to_string == courseid.to_string; });
        row.css('color', '#000000');
        restoreMe[courseid].appendTo( cell ); 
        //rm[0].courseid.appendTo( cell ); 
    } else {
        row.css('color', '#c0c0c0');
        restoreMe.push({courseid: course.detach()});
        }
});
});

您的代码存在一个根本问题,即 restoreMe 是一个数组而不是 JavaScript 对象。使它成为一个数组使得搜索项目变得困难(你需要循环遍历),并且也有可能重复条目(因为没有检查键)。

然而,对象可以构造为键值对,使键在整个对象中唯一。由于您拥有这些元素的唯一 ID,因此在对象中创建条目并从中检索会容易得多。

以下是我在您的代码中更改的部分:

...

var restoreMe = {};

...

restoreMe[courseid].appendTo( cell ); 

...

restoreMe[courseid] = course.detach();

最后,请查看此 working fiddle

restoreMe.push({courseid: course.detach()}); 将新词典添加到列表中,而不是词典中的新条目。

将其更改为 restoreMe[courseid] = course.detach();,因为它按预期工作。

我替换了数组 push,它现在可以工作了: restoreMe[课程编号] = course.detach();