简体   繁体   中英

jQuery/js: Completely remove object from JS by clicking on element in dom

So, when I have individual objects that display in a list. I'm trying to set up a delete feature which completely removes the object when you click on the li it is attached to. Any way to do this?

Here's some of my code:

employees = [];
employeesRole = [];
employeesWage = [];

function Employee(name, wage, role) { // object constructor
this.name = name; 
this.wage = wage;
this.role = role;
employees.push(this.name);
employeesRole.push(this.role);
employeesWage.push(this.wage);
}

Each individual object is stored in the arrays at the top. Now the jquery...

    $('#del').on('click', function(e){
    if('.over3') {
        $('.over3').hide(); // This is the class for each li 
    };
    $('#main').on('click', 'li', function(e){
        var deleted = $(this).closest('li');
        //$(this).closest('li').remove();
        deleted.remove();
    });

This only temporarily removes it, once I navigate back or refresh it appears again on the list. Any way to PERMANENTLY remove an object once clicked on?

Thanks!

When removing the list item, you're only removing the item itself and not the data inside the list item.

You'll need to perform an array splice to remove the data from your array.

array.splice(*indexInArray*,*numberOfElementsToRemove*)

once I navigate back or refresh it appears again on the list

That means browser reloads (aka rebuilds its DOM) the document again and so all items that you remove in runtime will appear again.

The only option doing so without server side change is to store id's/paths of removed elements in local storage and reapply removal inside your own $(document).ready(callback) .

Welcome to Stackoverflow Awbelton.

Javascript can't modify the outcome when you go back or refresh the page. I assume you want to make a AJAX request to a server telling it to remove it permanently from the file and or the database.

Another way to remove it is to remember it on the client side with say LocalStorage but this will only affect your browser and not any other user


PS: this expression will always evaluate to true, You might want to do some more logic here?

$('#del').on('click', function(e){    
if('.over3') {
    $('.over3').hide(); // This is the class for each li 
};

It's the same as running

$('#del').on('click', function(e){
    $('.over3').hide(); // This is the class for each li 

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