点赞功能在前端开发中非常常见,通常涉及到JavaScript和AJAX技术。下面是一个简单的点赞功能实现示例,包括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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="post">
<h2>这是一个帖子标题</h2>
<button id="likeButton" class="like-button">点赞 (0)</button>
</div>
<script src="script.js"></script>
</body>
</html>
.like-button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
document.addEventListener('DOMContentLoaded', function() {
const likeButton = document.getElementById('likeButton');
let likeCount = 0;
likeButton.addEventListener('click', function() {
likeCount++;
likeButton.textContent = `点赞 (${likeCount})`;
// 使用AJAX发送点赞请求到服务器
const xhr = new XMLHttpRequest();
xhr.open('POST', '/like', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('点赞成功');
}
};
xhr.send(JSON.stringify({ postId: 1 })); // 假设帖子ID为1
});
});
希望这个示例能帮助你理解并实现点赞功能。如果有更多具体问题,欢迎继续提问!
领取专属 10元无门槛券
手把手带您无忧上云