gpt4 book ai didi

javascript - 删除存储在 localStorage 中的数组中的一项

转载 作者:行者123 更新时间:2023-12-02 22:15:04 24 4
gpt4 key购买 nike

我将一些数据显示到表中,每行都有删除按钮,当单击按钮时,应该通过传递 id 和 来删除数组中存储在 localStorage 中的项目而不是将其分配回 LocalStorage。

HTML:

<table>
<tbody id="ResultProduct">
<tr class="RMAJS">
<td><input type="text" id="item1" name="itemName" value="Computer" /></td>
<td><a data-localstorage-id='ae90ac1a-64c4-49a7-b588-ae6b69a37d47' class="deletebtn">Delete</a></td>
</tr>
<tr class="RMAJS">
<td><input type="text" id="item2" name="itemName" value="Mobile" /></td>
<td><a data-localstorage-id='6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b' class="deletebtn">Delete</a></td>
</tr>
</tbody>
</table>

本地存储:

["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"]

0: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
1: "6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"

JavaScript:

$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem("users"));

for (var i = 0; i < getLocalStorage.length; i++) {
var Val = getLocalStorage[i]

//Here is my problem for example i want to delete this item
//"6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b" from array
//How can i do that ??

localStorage.setItem('users', JSON.stringify(??)); //Assign it back to LocalStorage.
}

$(targetElement).closest("tr.RMAJS").remove();
})

最佳答案

$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");

var getLocalStorage = JSON.parse(localStorage.getItem('users'));
getLocalStorage = getLocalStorage.filter(e => e !== getID);
localStorage.setItem('users', JSON.stringify(getLocalStorage));

$(targetElement).closest("tr.RMAJS").remove();
});

关于javascript - 删除存储在 localStorage 中的数组中的一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com