我正在尝试仅使用 html 和 javascript 来创建评论部分。当用户按下 post 时,我创建一个新的 dom 元素,但是当您刷新时,显然它会消失。我怎样才能让它永久添加。我想在没有数据库的情况下执行此操作,因为我以前从未使用过数据库。
这是 html:
<form class="commentForm">
<textarea name="comment" id="comment" rows="6" cols="50" required="required"></textarea><br>
<button type="button" class="btn btn-dark btn-submit" style="margin-right: 25%;" onclick="postComment()">Post</button>
</form>
JS:
function postComment() {
var message = document.getElementById("comment").value;
var div = document.createElement("div");
div.style.width = "500px";
div.style.height = "50px";
div.style.color = "black";
div.innerHTML = message;
document.getElementById("comments").appendChild(div);
document.getElementById("comment").value = "";
}
最佳答案
简短回答:使用localStorage
。
创建一个函数,其唯一目的是根据评论中的值添加一个 div:
function addNewDiv (message) {
var div = document.createElement('div');
div.style.width = '500px';
div.style.height = '50px';
div.style.color = 'black';
div.innerHTML = message;
document.getElementById('comments').appendChild(div);
};
要操作 localStorage,您应该使用 getItem
和 setItem
方法,如下所示:
function saveItem(message) {
var comments = JSON.parse(localStorage.getItem('comments') || '[]');
comments.push(message);
localStorage.setItem('comments', JSON.stringify(comments));
}
现在,更新您当前的函数以使用上面的函数:
function postComment() {
var message = document.getElementById('comment').value;
addNewDiv(message);
saveItem(message);
document.getElementById('comment').value = '';
}
您的所有评论都会保存。要在 F5 刷新时加载它们,请在 HTML 呈现后使用此脚本:
JSON.parse(localStorage.getItem('comments') || '[]').forEach(addNewDiv);
你已经完成了,要清除localStorage,请使用:
localStorage.clear();
或者:
localStorage.removeItem('comments');
希望有帮助。
关于javascript - 保持 html dom 操作刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460615/