I will bind read the json file by going through topmenu (an array of objects) and pull it out of it and save it in localstorage. everything works fine, and even the data is stored in localstorage. But my problem is that it stores data in localStorage in sorted order, which may be the default. But I don’t need it in sorted order, I want it to be in the order that it is present in json. Because when I store data in localstorage and read data from localstorage, it comes in sorted order. I can use the key in $ .each and add it to support our order if it is automatically sorted. But why does he sort himself. Is there any other job. Please help me solve this.
Note:
I need to save data to localStorage from json. Then read it from localstorage and donot read json until localstorage is completely empty. When I manually change the values in localstorage, it should reflect in the menu. I did all the conditional coding, I just need to find out the localstorage problem that stores it in sort order.
Below is my JSON file, javascript and partial html:
JSON
{
"topmenu":
[
{
"item": "File"
},
{
"item": "Help"
},
{
"item": "Edit"
},
{
"item": "View"
},
{
"item": "Go"
},
{
"item": "Tools"
},
{
"item": "Actions"
}
]
}
JAVASCRIPT
<script>
$(function() {
if (typeof localStorage === "undefined") {
alert("Sorry, your browser does not support web storage...");
}
$.getJSON("header.json", function(data) {
$.each(data.topmenu, function(key, val) {
localStorage.setItem(val.item, val.item);
});
loadMenu();
});
function loadMenu() {
$('.horizontalmenu').html('');
if (!localStorage.length < 1) {
for (var i = 0; i < localStorage.length; i++) {
var item = localStorage.getItem(localStorage.key(i));
$('.horizontalmenu').append('<li class="menu"><a href="#">' + item + '</a></li>');
}
} else {
$('.horizontalmenu').html("<li class='menu'>No menu</li>");
}
}
});
</script>
PARTIAL HTML
<div id="header">
<div id="header-title">
Test
</div>
<div id="header-menu">
<ul class="horizontalmenu">
</ul>
</div>
</div>
source
share