要在JavaScript中实现点赞功能,你需要考虑以下几个方面:
addEventListener
方法为点赞按钮添加点击事件。<button id="likeButton">点赞</button>
<span id="likeCount">0</span>
document.addEventListener('DOMContentLoaded', function() {
const likeButton = document.getElementById('likeButton');
const likeCount = document.getElementById('likeCount');
let isLiked = false; // 标记当前用户是否已经点赞
likeButton.addEventListener('click', function() {
if (isLiked) {
// 如果已经点赞,则取消点赞
unlike();
} else {
// 如果未点赞,则点赞
like();
}
});
function like() {
fetch('/api/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ action: 'like' })
})
.then(response => response.json())
.then(data => {
if (data.success) {
likeCount.textContent = data.likeCount;
isLiked = true;
likeButton.textContent = '取消点赞';
} else {
alert('点赞失败,请重试');
}
})
.catch(error => {
console.error('Error:', error);
alert('点赞失败,请重试');
});
}
function unlike() {
fetch('/api/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ action: 'unlike' })
})
.then(response => response.json())
.then(data => {
if (data.success) {
likeCount.textContent = data.likeCount;
isLiked = false;
likeButton.textContent = '点赞';
} else {
alert('取消点赞失败,请重试');
}
})
.catch(error => {
console.error('Error:', error);
alert('取消点赞失败,请重试');
});
}
});
const express = require('express');
const app = express();
app.use(express.json());
let likeCount = 0;
app.post('/api/like', (req, res) => {
const action = req.body.action;
if (action === 'like') {
likeCount++;
} else if (action === 'unlike') {
likeCount--;
} else {
return res.status(400).json({ success: false, message: 'Invalid action' });
}
res.json({ success: true, likeCount: likeCount });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上步骤和代码示例,你可以实现一个基本的点赞功能,并根据具体需求进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云