Javascript 如何从数组jQuery中取消推送数组?

Javascript 如何从数组jQuery中取消推送数组?,javascript,jquery,arrays,Javascript,Jquery,Arrays,这是我的代码: jQuery(document).on('click', '.list li', function(e){ var container = $('#button'); var selectedList = container.attr('data-selected-list'); if(jQuery(this).hasClass('done')){ jQuery(this).removeClass('done'); va

这是我的代码:

jQuery(document).on('click', '.list li', function(e){
    var container = $('#button');
    var selectedList = container.attr('data-selected-list');

    if(jQuery(this).hasClass('done')){
        jQuery(this).removeClass('done');

        var myElement = jQuery(this).attr('data-user-id');
        var myArray = selectedList;

        for (var i = myArray.length - 1; i >= 0; i--) {
          if (myArray[i] == myElement) myArray.splice(i, 1);
        }
        container.attr('data-selected-list', myArray);
    } else {
        jQuery(this).addClass('done');

        if (!selectedList) {
          selectedList = [];
        } else {
          selectedList = JSON.parse(selectedList);
        }

        selectedList.push(jQuery(this).attr('data-user-id'));
        selectedList = JSON.stringify(selectedList);

        container.attr('data-selected-list', selectedList);
    }
});
当用户单击列表时,我成功地创建了。我获取用户id并将其作为数组添加到数据选择列表中

我的问题是,当取消单击时,如何从数据选择列表(数组列表)中删除用户id


我在stackoverflow上搜索,但没有成功。

从数组中删除时需要使用
JSON.parse()
JSON.stringify()
,就像添加到数组中一样

if(jQuery(this).hasClass('done')){
    jQuery(this).removeClass('done');

    var myElement = jQuery(this).attr('data-user-id');
    var myArray = selectedList ? JSON.parse(selectedList) : [];

    for (var i = myArray.length - 1; i >= 0; i--) {
      if (myArray[i] == myElement) myArray.splice(i, 1);
    }
    container.attr('data-selected-list', JSON.stringify(myArray));
} 

另一种选择是使用
.data()
而不是
.attr()
。这将在jQuery内部存储信息,它可以存储任何类型。

使用
indexOf()
查找数组中元素的索引,使用
splice()
从数组中删除元素。@Barmar我尝试过,但失败了。您能帮我添加一个最终答案吗?抱歉,无法发布封闭问题的答案。如果您编辑问题以显示您尝试了什么,我可以重新打开它并发布一个带有更正的答案。@Barmar已完成,等待您。您需要
JSON.stringify(myArray)
将其存储回属性中。谢谢,但有一个错误:SyntaxError:missing:在条件表达式中,此错误位于(var myArray=selectedList?JSON.parse)(selectedList)?[];)我修正了我的打字错误真的非常感谢我现在从错误中吸取了教训再次感谢:)