简体   繁体   中英

Remove item from array and html list using jquery

I have a javascript array called names[] which stores names. (ofcourse) The names are also stored in list items in my html document, I have this code that removes a name when you click on it;

$(document).ready(function(){
    $(document).on('click', 'li', function(){
        $(this).remove();
    });
});

Can anyone tell me how I remove the same item from the array names[] ?

UPDATE: names[] is defined as follows:

function submit() {
    var theName = document.getElementById("enter").value;

    if (theName == "" || theName.length == 0) {
        return false;
    }

    names.push(theName);
    document.getElementById("name").children[0].innerHTML += "<li>" + names[names.length - 1] + "</li>";
    document.getElementById("enter").value = "";
}

This is done with an <input> .

Array.prototype.remove = function(item) {
    var index = this.indexOf(item);
    if (index > -1) {
        this.splice(index, 1);
        return true;
    }

    return false;
};    

$(document).ready(function(){
    $(document).on('click', 'li', function(){
        var text = $(this).text();
        names.remove(text);
        $(this).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