问题
I've been working on a tool to help people keep track of their cars in GTA, but I can't figure out how to remove them.
I've tried multiple things, but can't get it to work.
Here's my codepen https://codepen.io/Tristangre97/pen/dyoyOKw?editors=1010
function deleteItem(index) {
var existingEntries = JSON.parse(localStorage.getItem("allCars"));
existingEntries.splice(0, index); // delete item at index
}
回答1:
Splice won't update the local storage, instead, once you have removed the items you need to write the new array back to the local storage:
localStorage.setItem("allCars", existingEntries)
回答2:
function deleteItem(index) {
const existingEntries = JSON.parse(localStorage.getItem("allCars"));
existingEntries.splice(index, 1);
localStorage.setItem("allCars", JSON.stringify(existingEntries));
}
The first argument in splice is the index and the second one is the length. Also, you should save the new array into the localStorage.
回答3:
The CodePen provided works...so I'm assuming that it was corrected as the problem was the incorrect positions of the 2 parameters of the .splice()
Array method:
Original
/*
1st parameter is the index position of where within the array to start
2nd parameter is the quantity of array elements to remove
So this would always start at the beginning of the array and nth amount of elements
*/
existingEntries.splice(0, index);
Correct
/*
This will start at the specified index position and remove just that element
*/
existingEntries.splice(index, 1);
Demo
Details are commented in demo
Note: SO Stack Snippets block Web Storage API so to review a functioning demo, see this CodePen
// Reference the <form>
const list = document.forms.gtaList;
/*
Utility functions to get/set/show localStorage data
lsGet() and lsSet() are self-explanatory
the data will be either an array of objects or an empty array
viewList() renders a <button> for each entry of the data
*/
const lsGet = key => JSON.parse(localStorage.getItem(key)) || [];
const lsSet = (key, value) => localStorage.setItem(key, JSON.stringify(value));
const viewList = data => {
const display = list.elements.display;
display.value = "";
data.forEach((entry, index) => {
display.insertAdjacentHTML(
"beforeend",
`<button type='button' data-idx='${index}'>
${entry.address}
--==--
${entry.car}
</button><br>`
);
});
};
// Initial display of data if any in localStorage
viewList(lsGet("gtaData"));
// Register the click event to the <form>
list.onclick = autoList;
// Pass the event object (ie e)
function autoList(e) {
// Reference all form controls of <form> (ex. input, button, select, etc)
const gta = this.elements;
// Get current value of <select> and <input>
const address = gta.garage.value;
const car = gta.auto.value;
// Define empty object declare data
let entry = {};
let data;
/*
if the clicked tag (ie e.target) is a <button>...
and if clicked tag id is '#add'...
Get data from localStorage
Assign the values of <select> and <input> to the entry object
Add entry object to data array
*/
/*
...or if the clicked tag has [data-idx] attribute...
Get the [data-idx] value and convert it into a real Number
Next remove() the clicked <button> from the DOM
Get data from localStorage and splice() the object at the index
position designated by the clicked <button> [data-idx] Number
*/
/*
Display data as a group of <button>s
Finally set data to localStorage
*/
if (e.target.tagName === "BUTTON") {
if (e.target.id === "add") {
data = lsGet("gtaData");
entry.address = address;
entry.car = car;
data.push(entry);
}
if (e.target.hasAttribute('data-idx')) {
let idx = Number(e.target.dataset.idx);
e.target.remove();
data = lsGet("gtaData");
data.splice(idx, 1);
}
viewList(data);
lsSet("gtaData", data);
}
}
:root,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font: 700 3vw/1.2 Consolas;
}
form {
width: 90vw;
margin: 10vh auto;
}
input,
select,
button {
display: inline-block;
padding: 2px 5px;
font: inherit;
}
<form id="gtaList">
<select id="garage">
<option value="" selected>Select Location</option>
<option value="Little Bighorn Ave">Little Bighorn Ave</option>
<option value="Unit 124 Popular St">Unit 124 Popular St</option>
<option value="1 Strawberry Ave">1 Strawberry Ave</option>
<option value="142 Paleto Blvd">142 Paleto Blvd</option>
</select>
<input id="auto" placeholder="Mustang">
<button id="add" type="button">Add</button>
<fieldset>
<legend>Click to Remove</legend>
<output id="display"></output>
</fieldset>
</form>
来源:https://stackoverflow.com/questions/60103914/how-to-delete-certain-item-from-array-in-localstorage