I am using HTML5 and local storage to set / retrieve key/value pairs.
To set the value:
localStorage.setItem("003o000000BTRXz", "MyValue");
Then I utilized a function to loop through all stored items
for(var i = 0; i < localStorage.length; i++) {
var obj = localStorage.getItem(localStorage.key(i));
alert(obj);
}
The result is "MyValue" and I would like it to be "003o000000BTRXz".
What would be the proper syntax to get this?
Use localStorage.key(i)
to get the key:
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
alert(key + ": " + value);
}
All browsers, especially the old ones might sometimes not support localstorage api included in HTML5. Thus it is advisable to first check if your browser supports it like so,
if(typeof(Storage) !== "undefined") {
// Have fun with localstorage! :)
} else {
// alert something saying doesn't support
}
Use the localstorage api like so,
// Store
localStorage.setItem("key", "Value");
// Retrieve
localStorage.getItem("key");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.