js实现简易留言板,当“昵称”和“留言内容”文本框内输入信息后,单击“单击这里提交留言”按钮,输入的信息会显示在页面上端的留言板中,若没有输入“昵称”和“留言内容”,单击“单击这里提交留言”按钮时不能发送留言
时间: 2023-06-19 08:08:38 浏览: 175
这里提供一个简单的实现方式:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>留言板</title>
<style>
#message-board {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div>
<label for="name">昵称:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="message">留言内容:</label>
<textarea id="message" name="message"></textarea>
</div>
<div>
<button id="submit">单击这里提交留言</button>
</div>
<div id="message-board"></div>
<script src="message_board.js"></script>
</body>
</html>
```
JS代码:
```javascript
// 获取元素
const nameInput = document.getElementById('name');
const messageInput = document.getElementById('message');
const submitButton = document.getElementById('submit');
const messageBoard = document.getElementById('message-board');
// 定义保存留言的数组
let messages = [];
// 提交留言函数
function submitMessage() {
// 获取输入框的值
const name = nameInput.value.trim();
const message = messageInput.value.trim();
// 判断是否为空
if (name === '' || message === '') {
alert('请输入昵称和留言内容!');
return;
}
// 将留言保存到数组中
messages.push({ name, message });
// 清空输入框的值
nameInput.value = '';
messageInput.value = '';
// 渲染留言板
renderMessageBoard();
}
// 渲染留言板函数
function renderMessageBoard() {
// 清空留言板
messageBoard.innerHTML = '';
// 循环遍历留言数组,生成 HTML 代码并添加到留言板中
messages.forEach((item) => {
const messageItem = document.createElement('div');
messageItem.innerHTML = `<strong>${item.name}:</strong>${item.message}`;
messageBoard.appendChild(messageItem);
});
}
// 绑定按钮的点击事件
submitButton.addEventListener('click', submitMessage);
```
以上代码实现了一个简单的留言板,当单击“单击这里提交留言”按钮时,会将输入的昵称和留言内容保存到一个数组中,并且清空输入框的值,然后重新渲染留言板。如果输入框中有一个或多个为空,则会弹出提示框。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)