I have a site where users can create divs with a button, and then add text to them. I could save the text to the local storage, but I'd also like to save the divs and their state, like where they are positioned etc. so they stay the same after a refresh. As far as I'm aware, divs cannot be stored in the local storage in the same way. Any ideas?
我有一个网站,用户可以创建一个按钮的div,然后添加文本到他们。我可以将文本保存到本地存储,但我也想保存div及其状态,如它们的位置等,以便它们在刷新后保持不变。据我所知,div不能以同样的方式存储在本地存储中。有什么主意吗?
更多回答
You could save the div's information in an object or an array of objects and then save that in the local storage or a DB or which ever way of saving data you like. To give a more specific answer, you would need to provide some code.
您可以将div的信息保存在一个对象或一个对象数组中,然后将其保存在本地存储或DB中,或者您喜欢的任何保存数据的方式。要给出更具体的答案,您需要提供一些代码。
优秀答案推荐
If localStorage
is what you want to use, you could serialize the state of each div to an object, and store that object (or an array of objects) into localStorage using JSON.stringify
and convert it back into the object/array form with JSON.parse
.
如果您想使用本地存储,您可以将每个div的状态序列化为一个对象,并使用JSON.stringify将该对象(或对象数组)存储到本地存储中,然后使用JSON.parse将其转换回对象/数组形式。
You wouldnt store the div itself in local storage. Instead of an array of strings, like
您不会将div本身存储在本地存储中。而不是字符串数组,如
[
"Text 1",
"Text 2"
]
Start to think about an array of objects:
开始考虑一组对象:
[
{
text: "Text 1",
top: 100,
left: 200
},
{
text: "Text 2",
top: 400,
left: 750
},
]
You can then convert this array to JSON and store that in local storage instead.
然后,您可以将该数组转换为JSON并将其存储在本地存储中。
更多回答
我是一名优秀的程序员,十分优秀!