-2

I have a school project and I need to make a music website, it's almost finished, but I'm having problems doing the playlist with web local storage.

'use strict' const configs = { PLAYLIST_KEY: "playlist", }; function addMusicToPlaylist(data) { let musics = new Array(); if (localStorage.hasOwnProperty(configs.PLAYLIST_KEY)) { musics = JSON.parse(localStorage.getItem(configs.PLAYLIST_KEY)); } musics.push(data); localStorage.setItem(configs.PLAYLIST_KEY, JSON.stringify(musics)); } $(".add-music-button").on("click", function () { let musicRef = $(this).data("ref"); let musicObject = { author: $(`#${musicRef} .music-author`).html(), title: $(`#${musicRef} .music-title`).html(), }; addMusicToPlaylist(musicObject); }); $(document).ready(function () { if ($("#playlist-table").length > 0) { if (localStorage.hasOwnProperty(configs.PLAYLIST_KEY)) { // testa se o objecto tem a propriedade especificada JSON.parse(localStorage.getItem(configs.PLAYLIST_KEY)).map( (music, index) => { $("#playlist-table").append(` <tr id="music-${index}"> <td class="music-author">${music.author}</td> <td class="music-title">${music.title}</td> </tr> <tr><td><p class="textoFav"></p></td> musica<td><button class="favBotao" onclick="apagar()" ><i class="fa fa-remove"></i></button></td></tr> `); } ); } } }); function apagar (){ localStorage.removeItem('playlist') } 

I only can remove all of the musics inside the playlist, but i want to remove only one music, like this:

"button 1 : music 1

button 2 : music 2

button 3 : music 3

button 4 : music 4"

If the user presses button 3, I want it to delete from the playlist, the music 3. How can I do that?

2
  • 3
    You should setItem(musics) where musics is array of elements without one that you wish to delete - you must update local storage item content, not delete it completely. Commented Jan 12, 2021 at 14:19
  • Don't think about it as "the music in local storage"; think about it as an array of items. How do you delete an item from an array? slice. Once you have the array the way you want it, serialize and store it in local storage. Commented Jan 12, 2021 at 14:23

1 Answer 1

0

Set an index argument, i.e: onclick="apagar(index)".

Then, create apagar function:

function apagar(index) { let musics = new Array(); musics = JSON.parse(localStorage.getItem(configs.PLAYLIST_KEY)); musics = musics.filter((_, i) => i !== index); localStorage.setItem(configs.PLAYLIST_KEY, JSON.stringify(musics)); } 
Sign up to request clarification or add additional context in comments.

2 Comments

if i set and index argument in "onclick = "apagar(index)" gives me and error saying :" index is not defined
Use string interpolation: apagar(${ index })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.