写个html聊天页,用localstorage 存最近5条聊天记录,重新打开页面时再读取出来
1写个html聊天页,用localstorage 存最近5条聊天记录,重新打开页面时再读取出来




聊天







var chatLog = JSON.parse(localStorage.getItem('chatLog')) || [];
var chatBox = document.getElementById('chatbox');
var textInput = document.getElementById('textinput');

// 显示最近5条聊天记录
for (var i = 0; i < 5 && i < chatLog.length; i++) {
var chatMsg = document.createElement('p');
chatMsg.innerText = chatLog[chatLog.length - 1 - i];
chatBox.appendChild(chatMsg);
}

function sendMessage() {
var message = textInput.value;
chatLog.push(message);
localStorage.setItem('chatLog', JSON.stringify(chatLog));

var chatMsg = document.createElement('p');
chatMsg.innerText = message;
chatBox.appendChild(chatMsg);

textInput.value = '';
}


本页由《梦行文档》生成

 

name完成
30