简体   繁体   中英

Remove clicked item from list JQuery

I have a simple list where you can add items in html/jquery. I want to remove a specific item when i click on it in the list. I can add items, they show up but the remove code is not working.

Remove code

$('#items a.delete').on('click', function(){
$(this).parent().remove();
});

This is my code:

$(document).on('pagebeforeshow', '#home', function(event) {
homepage();
});

$('#items a.delete').on('click', function(){
 $(this).parent().remove();
});

function homepage(){
   // Fetch the existing objects
   objects = getObjects();

   // Clear the list
   $('#items').find('li').remove();

   // Add every object to the objects list
   $.each(objects, function(index, item){
       element = '<li data-icon="delete"><a href="#" class="delete">'+item.title+'</a></li>';

       $('#items').append(element);
   });

   $('#items').listview();
   $('#items').listview("refresh");
}

function getObjects(){
   // See if objects is inside localStorage
   if (localStorage.getItem("objects")){
       // If yes, then load the objects
       objects = JSON.parse(localStorage.getItem("objects"));
   }else{
       // Make a new array of objects
       objects = new Array();

   }
   return objects;
}

homepage() gets called when you enter the page, it repopulates the list. Objects are stored in localstorage.

HTML: <ul id="items" data-role="listview" data-inset="true"></ul> <br>

You are binding the events before you are appending them to the DOM. When the elements are then appended, you'll need to bind the event after , or use event delegation to find that element. A possible fix would be to move this code block

$('#items a.delete').on('click', function(){
    $(this).parent().remove();
});

after you call the homepage() function.

You are dynamically adding new elements, so you need to target the parent element on your event binding:

$('#items').on('click', 'a.delete', function(){
   $(this).parent().remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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