简体   繁体   中英

Removing objects from an array onclick

I have a an array of items which holds item objects. I want to create a function that when I click on a certain item it is removed from the array. I know I need to use something like splice and I have implemented the following solution but it does the seem to work.

Can anyone tell me what am I doing wrong.

function updateView() {


for (var i = 0; i < storeItems.length; i++) {
    output += "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>" 
    + storeItems[i].title + " " + "\n" + "</a>";

   }

function removeRecord(i) {

    storeItems.splice(i, 1);
    var newItem = "";

    // re-display the records from storeItems.

    for (var i = 0; i < storeItems.length; i++) {
        newItem += "<a href='#' onclick='removeRecord(" + i + ");'>X</a> " 
        + storeItems[i] + " <br>";
    };
    document.getElementById('foods').innerHTML = newItem;
}

I think this the error is in the line below:

output  +=  "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>" +  storeItems[i].title + " " + "\n" + "</a>"; 

Because it does not recognise the "onclick" event even when I try to do a test with a simple alert.

Can anyone tell me what am I doing wrong. Also if you think you need more information to answer this question please let me know.

Thank you in advance.

Try ...

storeItems = storeItems.splice(i, 1);

WRONG : Basically, you have to assign the spliced array to something.

UODATE :

Here's the way I would do it ... tested in jsFiddle :

var storeItems = [{
    title: "Dog"
}, {
    title: "Cat"
}, {
    title: "Bird"
}];

var foods = document.getElementById('foods');
foods.addEventListener('click', function(e) {
    var index = e.target.getAttribute('value');
    storeItems.splice(index, 1);

    // re-display the records from storeItems.
    updateView();
});

function updateView() {
    var output = "";
    for (var i = 0; i < storeItems.length; i++) {
        output += "<a href='#' class='item' value='" + i + "'>" + storeItems[i].title + " " + "\n" + "</a>";

    }
    document.getElementById('foods').innerHTML = output;
}


updateView();

HTML:

<div id='foods'></div>

This effectively takes the onclick event off of the anchor tag (you could have them on any type of tag at this point) and I also reused your updateView code in the Listener so that it only needs maintained in one location.

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