How to save functions in localStorage API HTML5
This question already has an answer here:
Few observations :
JSON . Look into the official document json.org. string in double quotes, or a number , or true or false or null , or an object or an array but not a method . You can use JSON.stringify replacer function to convert the function into string while converting to JSON string.
DEMO
var storage = {
getListUsers: function() {
return {
name: 'name',
age: 'age'
}
},
active: true,
data: []
}
var json = JSON.stringify(storage, function(key, value) {
if (typeof value === 'function') {
return value.toString();
} else {
return value;
}
});
console.log(json); You can set the JavaScript which should be set at localStorage as .textContent of a <script> element, get the .textContent of the element to set at localStorage . You can then set the same text at a different <script> element or convert the text to a data URI which can be posted to other browsing contexts or a server.
<script id="storage">
/* Example code */
var storage = {
getListUsers: function() {
return {
name: 'name',
age: 'age'
}
},
active: true,
data: []
}
</script>
<script>
var convert = document.getElementById("storage");
localStorage.setItem("data", convert.textContent);
console.log(localStorage.getItem("data"));
</script>
链接地址: http://www.djcxy.com/p/27942.html
上一篇: 以字符串形式接收对象
