如何根据您使用javascript单击的项目从数组中删除特定项目

时间:2022-06-12 04:00:17

I want to be able to click on a list item(which is made from the items of the array) and remove it permanently from the array. I am able to remove it when clicked using remove(), but when I add another item to the array the item shows back, plus the new item i just added.

我希望能够单击列表项(由数组的项目组成)并从阵列中永久删除它。我可以在使用remove()单击时删除它,但是当我向数组中添加另一个项目时,项目显示回来,加上我刚添加的新项目。

JSFIDDLE account: http://jsfiddle.net/trav5567/3s64o1ta/1/

JSFIDDLE帐户:http://jsfiddle.net/trav5567/3s64o1ta/1/

Javascript

使用Javascript

      function testArray(){
       var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];
       function initArray(){
        loopArray();
       }initArray();
       function myFruit(){
         $('#addFruit').on('click', function(e) {
          e.preventDefault();
          var flag = true;
          var val = $('#fruitAdd').val();
          for(var i = 0 ; i < Fruit.length ; i ++){
            if(Fruit[i] == val){
              flag = false;
              console.log('already entered this item');
             }        
           }
           if(flag){
            Fruit.push(val);
            loopArray();
           }
         });
         }myFruit();
         function loopArray(){
           var fruitList = $('ul.fruit');
           var arrayContainer = $('.arrayContainer');
           fruitList.empty();
           for(var i = 0; i< Fruit.length; i++){
             fruitList.append('<li>'+Fruit[i]+'</li>');
           }
          }
         function removeItem(){
            var itemClicked = $('ul.fruit li');
            itemClicked.on('click', function(){
               $(this).remove();
            });
         }removeItem();
       }testArray();

1 个解决方案

#1


1  

You are not removing item from array when clicked, you are just removing the li tag which contains element when clicked, for to remove element from array also when clicked on item's li, you have to use splice method to remove element from array as

单击时不是从数组中删除项目,只是在单击时删除包含元素的li标记,为了从数组中删除元素,当单击项目的li时,必须使用splice方法从数组中删除元素

    var itemClicked = $('ul.fruit li');
       itemClicked.on('click', function () {
       $(this).remove();
       var item = $(this).text();
       var index = Fruit.indexOf(item);
      Fruit.splice(index,1);
   });

Check the Working Fiddle Here

检查这里的工作小提琴

#1


1  

You are not removing item from array when clicked, you are just removing the li tag which contains element when clicked, for to remove element from array also when clicked on item's li, you have to use splice method to remove element from array as

单击时不是从数组中删除项目,只是在单击时删除包含元素的li标记,为了从数组中删除元素,当单击项目的li时,必须使用splice方法从数组中删除元素

    var itemClicked = $('ul.fruit li');
       itemClicked.on('click', function () {
       $(this).remove();
       var item = $(this).text();
       var index = Fruit.indexOf(item);
      Fruit.splice(index,1);
   });

Check the Working Fiddle Here

检查这里的工作小提琴