gpt4 book ai didi

javascript - 刷新页面返回 [object CSSStyleDeclaration]

转载 作者:行者123 更新时间:2023-11-28 02:20:16 25 4
gpt4 key购买 nike

当我编辑内容并保存更改时,它会在刷新页面时显示 [object CSSStyleDeclaration] 而不是我更新的内容。

function newElement() {
let li = document.createElement("li");
let inputvalue = document.querySelector("#myInput").value;
let savedNote = document.createTextNode(inputvalue);
li.appendChild(savedNote);
if (inputvalue === '') {
alert("Please write something")
} else {
document.querySelector("#myNotes").appendChild(li);
}
document.querySelector("#myInput").value = '';
}

function saveEdits() {
let editElement = document.querySelector("#saved-notes");
editElement = document.querySelector("#myNotes");
let userVersion = editElement.innerHTML;
userVersion = editElement.style;
localStorage.userEdits = userVersion;
document.querySelector("#update").innerHTML = "Edits saved. Refresh the page to see changed content";
}

function checkEdits() {
if (localStorage.userEdits != null)
document.querySelector("#saved-notes").innerHTML = localStorage.userEdits;
document.querySelector("#myNotes").style = localStorage.userEdits;
}
ul {
margin: 0;
padding: 0;
}

ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
background: #eee;
font-size: 18px;
transition: 0.2s;
}
<html>

<head>
<meta charset="utf-8">
</head>

<body onload="checkEdits()">

<div id="myDiv" class="new-note">
<textarea id="myInput"></textarea><br>
<button onclick="newElement()" class="save-button">Create</button>
<button onclick="saveEdits()" class="edit-button">Save Changes</button>
</div>

<div id="update"></div>
<div id="saved-notes"></div>
<ul id="myNotes">
</ul>

</body>

</html>

如果我删除 userVersion = editElement.style; 会起作用,但不会有 CSS 样式。只是纯文本。

我想了解为什么会发生这种情况并从中吸取教训。提前致谢。

最佳答案

因为函数localStorage.set只能保存String,所以在Object被存储前会调用.toString(),结果为它是 [object CSSStyleDeclaration] 类型。在保护它之前,您是否尝试过对其进行字符串化?userVersion = JSON.stringify(editElement.style);document.querySelector("#myNotes").style = JSON.parse(localStorage.userEdits);

关于javascript - 刷新页面返回 [object CSSStyleDeclaration],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076933/

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