简体   繁体   中英

Update variables after arr.splice()

I have an array that I am using to populate div's and assign their ID's with numbers based on where they lie in the array.

I am able to remove a section using .splice() , but after I remove the element, the ID's remain the same on the element, (which is affecting how I delete subsequent items in the same array) until I refresh the page.

For example it starts out as

<div id="favorites-1"></div>
<div id="favorites-2"></div>
<div id="favorites-3"></div>

when I remove one of the divs, say <div id="favorites-1"></div> I would like <div id="favorites-2"></div> to now become the new <div id="favorites-1"></div> and the favorites-3 to becomes favorites-2.

If i remove the elements from right to left it works. If i remove the elements from left to right, only the first element is actually removed.

How can I update the ID numbers based on their location with JavaScript or jQuery?

//splice the array
arr.splice(x,y,replacements)
//iterate from the first modified item in the list and set the correct ID 
for(var i=x; i<arr.length; i++) {
    arr[i].id = "favorites-"+i;
}

is the manual way.

But if you want to do a lot of things like this, I'd recommend using Knockout.js or a similar library. With knockout, you'd have an observable array of items which you could add items to, and you could map the id to the index of the element in an automatic way. For instance it might look something like this.

<!-- ko foreach: myItems -->
<div data-bind="attr:{id:'favorites-'+$index"></div>
<!-- /ko -->

You can also do this with other libraries such as AngularJS or EmberJS, but knockout is a focused library for the particular problem of binding your data-model to the DOM.

You can achieve a sparse array with delete (then you wouldn't need to change your elements' IDs):

var a = [0,1,2,3];
delete a[1]; // Key "1" was deleted

Caveat

The length of the array will still be 4 , even without the 1 key. If you're looping the array based on length, you'll get undefined for a[1] . If you iterate with for..in , you'll skip from key "0" to "2" , but that might cause other problems ...

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