gpt4 book ai didi

javascript - localStorage 已保存,但网页重新加载后无法在浏览器上保留数据

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:07 25 4
gpt4 key购买 nike

我试图将聊天消息保存在localStorage(或sessionStorage)上并显示在网页上,我可以找到存储在Devtool -> application -> localStorage中的键值对,每次用户发送消息时消息值都会更新并显示在网页上。然而,每次页面重新加载时内容都会消失。怎么解决这个问题?

我遇到的是将消息保存到数组的push()将替换而不是添加值,不确定这两个问题是否相关。谢谢。

哈巴狗文件

#test2(style='height:200px; width:200px; border:1px solid #ccc')

js文件

$('#sendMessage').on('click', function() {

var msg = $('#message').val()
var messages = [];
console.log(typeof(messages)); //obj
messages.push(msg);
console.log(messages); //array value
if (localStorage) {
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
localStorage.setItem('username', $('#username').val());
localStorage.setItem('date', currentTime());

var cUser = localStorage.getItem('username');
var cMsg = localStorage.getItem('message');
var cTime = localStorage.getItem('date');

} else {
console.log('localStorage is not supported.');
}

document.getElementById("test2").innerHTML += "<div>" + cUser + " : " + cMsg + "</div>";
// Clear the field
$('#message').val('');
}); // End click

重新加载页面丢失数据

    // Send Message
$('#sendMessage').on('click', function() {
// get value
var username = $('#username').val();
var msg = $('#message').val();
var time = currentTime();

//check if localStorage works and create msgArray

if (!localStorage) {

console.log('localStorage is not supported.');

} else {

//check if there is existing message array in msgArray
var msgArray = localStorage.getItem('message');
//if there is NULL, setup msgArray = [], converts a JavaScript value to a JSON string
if (JSON.stringify(msgArray) == 'null') {
msgArray = [];
} else {
//else parses a JSON string, constructing the JavaScript value or object described by the string
msgArray = JSON.parse(msgArray);
}
}

//add new message object to msgArray

var newMsg = {
msg: msg,
username: username,
time: time
};

msgArray.push(newMsg);
// stringsfy the message and store it to localStorage
localStorage.setItem('message', JSON.stringify(msgArray));

// dispaly current messages

var cMsg = JSON.parse(localStorage.getItem('message'));
// console.log(cMsg); // should shows list of array with new added message objects
// for (var i = 0, max = cMsg.length; i < max; i++) {

//document.getElementById("test2").innerHTML += "<div>" + cMsg[i].username + " : " + cMsg[i].msg + " at " + cMsg[i].time + " </div>";
$('#test2').append('<div class="well well-sm">' + cMsg[cMsg.length - 1].username + ' : ' + cMsg[cMsg.length - 1].msg + ' <span class="pull-right"><small id="date"> at ' + cMsg[cMsg.length - 1].time + '</small></span></div>');

// load the bottom of message
var objDiv = document.getElementById("chatArea");
objDiv.scrollTop = objDiv.scrollHeight;

// Clear the field
$('#message').val('');
}); // End click

最佳答案

我不确定你想用 for 循环来完成什么,因为你似乎多次设置相同的值,就像你有消息一样(本质上这是没有值(value)的,设置一次就足够了)

让我们回顾一下您的步骤:

您正在从带有 id message 的输入元素获取一个值,并将其保存到 msg 变量中

var msg = $('#message').val()

构建一个新数组,并将其插入

var messages = [];
messages.push(msg);

然后迭代该数组,但重新使用 msg 变量

for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}

所以本质上,你这样做了:

localStorage.setItem('message', $('#message').val());

仅此而已。也许您想先获取消息数组,然后将新消息添加到其中,而不是像下面这样

function addMessage() {
// get the potential array
var messages = JSON.parse( localStorage.getItem('message') || '[]' );
// add the message
messages.push($('#message').val());
// save the array as a string, using JSON.stringify
localStorage.setItem('message', JSON.stringify( messages));
// empty the message value
$('#message').val('');
console.log(messages);
}

关于javascript - localStorage 已保存,但网页重新加载后无法在浏览器上保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127766/

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