代码之家  ›  专栏  ›  技术社区  ›  whatbox

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

  •  0
  • whatbox  · 技术社区  · 7 年前

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

    JSFIDLE(JSIDLE): 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()});
            }
    });
    });
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   Helio Santos    7 年前

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

    将其更改为 restoreMe[courseid] = course.detach(); 正如预期的那样。

        2
  •  0
  •   31piy    7 年前

    你的代码有一个根本问题,那就是 restoreMe 是一个数组,而不是JavaScript对象。将其设置为数组会使搜索项目变得困难(您需要循环),并且还可能会创建重复的条目(因为没有对键进行检查)。

    但是,对象可以构造为键值对,使键在整个对象中唯一。由于这些元素具有唯一的ID,因此在对象中创建条目并从中检索将更加容易。

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

    ...
    
    var restoreMe = {};
    
    ...
    
    restoreMe[courseid].appendTo( cell ); 
    
    ...
    
    restoreMe[courseid] = course.detach();
    

    最后,看看这个 working fiddle .

        3
  •  0
  •   whatbox    7 年前

    我更换了阵列推送,现在可以工作了: restoreMe[课程ID]=课程。分离();