gpt4 book ai didi

javascript - jQuery - 本地存储排序字符串化对象顺序

转载 作者:行者123 更新时间:2023-11-29 21:35:36 25 4
gpt4 key购买 nike

我有一个对象 menuItems,它是 JSON 字符串化的(其中包含 3 个对象)并保存在本地存储中。它作为 result 从服务器返回。

localStorage.setItem('menuItems', JSON.stringify(result));

menuItems 中的 3 个对象是:

{
id: "1"
item: "Apple",
type: "fruit"
},
{
id: "2"
item: "Banana",
type: "fruit"
},
{
id: "3"
item: "Carrot",
type: "vegetable"
}

我从本地存储中获取 menuItms,遍历其对象,并按照与上面相同的顺序获取下面的列表,这是完美的。不过,我想对它们进行排序,并将新顺序重新保存到本地存储,因此在遍历它们时,我在 data-sort-id 中输出每次迭代的索引。

<ul class="sort-menu-items-list">
<li data-sort-id="0">Apple is a fruit</li>
<li data-sort-id="1">Banana is a fruit</li>
<li data-sort-id="2">Carrot is a vegetable</li>
</ul>

在前端对它们进行排序后,我得到以下作为最终排序顺序。我想将对象 menuItems 重新保存在本地存储中,以便始终按新顺序检索它们:

<ul class="sort-menu-items-list">
<li data-sort-id="2">Carrot is a vegetable</li>
<li data-sort-id="0">Apple is a fruit</li>
<li data-sort-id="1">Banana is a fruit</li>
</ul>

如何将 menuItems 对象的新 2、0、1 排序顺序保存到本地存储,以便在我检索 menuItems 时它以新顺序出现?我认为 data-sort-id 应该会有所帮助,但不确定如何继续将新订单重新保存到本地存储。有什么想法吗?

更新:

$('.sort-done').click(function(){
var newSortIds = [];
$('.sort-menu-items-list').find('li').each(function(){
newSortIds.push($(this).data('sort-id'));
});
console.log(newSortIds); // ["2","0","1"]
});

我需要在上面的代码中添加什么才能使其在 jQuery 中工作?

这是 fiddle :http://jsfiddle.net/D2NtS/294/

最佳答案

这样的事情可能会有所帮助

var fruits = [{
id: "1",
item: "Apple",
type: "fruit"
}, {
id: "2",
item: "Banana",
type: "fruit"
}, {
id: "3",
item: "Carrot",
type: "vegetable"
}];

var sortorder = [2, 0, 1]; // get this from localStorage

var i = 0,
list = document.querySelectorAll("li"),
len = fruits.length;

for (i; i < len; i++) {
var ord = sortorder[i];
list[i].innerHTML = fruits[ord].item + " is a " + fruits[ord].type;
list[i].setAttribute("data-sort-id", ord);
}

document.getElementById("btn").onclick = function() {
var ord = [];
var a = 0;

for (a; a < len; a++) {
ord.push(Number(list[a].getAttribute("data-sort-id")))
}
alert(JSON.stringify(ord)) // set this to localStorage
}
<ul>
<li></li>
<li></li>
<li></li>
</ul>
<input type="button" id="btn" value="get order">

关于javascript - jQuery - 本地存储排序字符串化对象顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34959171/

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