简体   繁体   English

如何使用 jquery $this 从列表中删除特定的 object?

[英]How to remove specific object from list using jquery $this?

I have some table with checkboxes in row and after clicking on them I would like to add/remove their data to list as a object.我有一些带有复选框的表格,单击它们后,我想添加/删除它们的数据以列为 object。 I did already adding object to list but im struggling with removing object which i clicked.我确实已经将 object 添加到列表中,但我正在努力删除我点击的 object。

   var myList = [];

    $('.addMe').click(function() {
        var tr = $(this).parent('td').parent('tr');
        var id = $(tr).children('.col-id').text();
        var zxc = $(tr).children('.col-zxc').text();

        if ($(this).hasClass('added')){
            **myList.filter(function(value){
                return value.id !== id;
            });**
            console.log('removing: '+id);
        }
        else{
            myList.push({id,zxc});
            console.log('adding: '+id);
        }

        console.log(myList);
      });

This part is not working:这部分不起作用:

myList.filter(function(value){
                    return value.id !== id;
                });

So when I added 4 elements:因此,当我添加 4 个元素时:

myList = [ {id:'1', zxc:'test'}, {id:'2', zxc:'test1'}, {id:'3', zxc:'test2'}, {id:'4', zxc:'test3'}]

I would like to remove for example 3rd element clicking on third checkbox and result will be:我想删除例如点击第三个复选框的第三个元素,结果将是:

myList = [ {id:'1', zxc:'test'}, {id:'2', zxc:'test1'}, {id:'4', zxc:'test3'}]

I tried using filter(), grep() but I cant make it work.我尝试使用 filter()、grep() 但我无法使其工作。

Here is jsfiddle with full code and how its working: https://jsfiddle.net/1rm6pwqk/这是带有完整代码的 jsfiddle 及其工作原理:https://jsfiddle.net/1rm6pwqk/

The filter method does not mutate the array on which it is invoked. filter 方法不会改变调用它的数组。 Instead it returns a new array with the elements that satisfy the predicate.相反,它返回一个新数组,其中包含满足谓词的元素。 Assign the returned value to your myList variable to update it:将返回值分配给您的 myList 变量以更新它:

myList = myList.filter(function(value){
                return value.id !== id;
            });

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

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