js本地存储留言板案例
时间: 2023-08-08 16:10:12 浏览: 60
好的,下面是一个简单的基于本地存储的留言板案例:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>本地存储留言板</title>
<style>
textarea {
width: 300px;
height: 100px;
}
li {
list-style-type: none;
margin-bottom: 10px;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>本地存储留言板</h1>
<textarea id="message"></textarea>
<button id="submit">提交</button>
<ul id="messageList"></ul>
<script src="message.js"></script>
</body>
</html>
```
JavaScript代码:
```
// 获取留言列表
function getMessageList() {
let messageList = localStorage.getItem('messageList') || '[]';
return JSON.parse(messageList);
}
// 保存留言列表
function saveMessageList(messageList) {
localStorage.setItem('messageList', JSON.stringify(messageList));
}
// 添加留言
function addMessage(message) {
let messageList = getMessageList();
messageList.push(message);
saveMessageList(messageList);
}
// 渲染留言列表
function renderMessageList() {
let messageList = getMessageList();
let messageListHtml = '';
for (let i = 0; i < messageList.length; i++) {
messageListHtml += '<li>' + messageList[i] + '</li>';
}
document.getElementById('messageList').innerHTML = messageListHtml;
}
// 初始化
function init() {
renderMessageList();
document.getElementById('submit').addEventListener('click', function() {
let message = document.getElementById('message').value.trim();
if (message) {
addMessage(message);
renderMessageList();
document.getElementById('message').value = '';
}
});
}
init();
```
这个留言板的实现思路是利用localStorage来保存留言列表,通过JavaScript的API对localStorage进行读取和写入操作,通过DOM操作来渲染留言列表和添加留言。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)