JavaScript 实现评论功能主要涉及前端页面的设计与交互逻辑。以下是一个简单的示例,展示了如何使用 JavaScript 来实现一个基本的评论系统。
以下是一个简单的 HTML、CSS 和 JavaScript 结合的评论系统示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>评论系统示例</title>
<style>
.comment {
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ccc;
}
.comment input[type="text"] {
width: 80%;
padding: 5px;
}
.comment button {
padding: 5px 10px;
}
</style>
</head>
<body>
<div id="comments">
<!-- 评论将在这里动态添加 -->
</div>
<div class="comment">
<input type="text" id="newComment" placeholder="输入你的评论">
<button onclick="addComment()">提交评论</button>
</div>
<script>
function addComment() {
const commentText = document.getElementById('newComment').value;
if (commentText.trim() === '') return; // 防止空评论
const commentsDiv = document.getElementById('comments');
const newCommentDiv = document.createElement('div');
newCommentDiv.className = 'comment';
newCommentDiv.textContent = commentText;
// 添加删除按钮
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除';
deleteButton.onclick = function() {
commentsDiv.removeChild(newCommentDiv);
};
newCommentDiv.appendChild(deleteButton);
commentsDiv.insertBefore(newCommentDiv, document.querySelector('.comment'));
document.getElementById('newComment').value = ''; // 清空输入框
}
</script>
</body>
</html>textContent 而不是 innerHTML 来插入文本,避免执行潜在的恶意脚本。通过上述方法,可以构建一个简单而有效的评论系统,并确保其稳定性和安全性。