[英]How to refresh just one DOM element using JS vanilla
I'm using DOM to create an element for me that shows the amount of likes a specific comment has received.我正在使用 DOM 为我创建一个元素,显示特定评论收到的点赞数量。 When someone likes the button that data gets pushed to the API.当有人喜欢数据被推送到 API 的按钮时。 However, in order to see the number of likes increase I have to manually reload the page.但是,为了看到喜欢的数量增加,我必须手动重新加载页面。
Is there a way to automatically refresh that specific DOM element so that when a user clicks the like button the amount of likes will automatically increase (so refresh) without having to manually reload the website?有没有办法自动刷新那个特定的 DOM 元素,这样当用户点击喜欢按钮时,喜欢的数量会自动增加(所以刷新),而无需手动重新加载网站?
// shows the amount of likes
const likeCounter = document.createElement("p");
likeCounter.classList.add("comments__container-content-like-counter");
functionsDiv.appendChild(likeCounter);
likeCounter.innerText = commentData.likes;
// likes a comment and adds it to the api
commentLike.addEventListener("click", () => {
const addLike = commentData.id;
axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
console.log("Like has been added!");
});
});
Here you go:这里是 go:
// shows the amount of likes
const likeCounter = document.createElement("p");
likeCounter.classList.add("comments__container-content-like-counter");
functionsDiv.appendChild(likeCounter);
likeCounter.innerText = commentData.likes;
// likes a comment and adds it to the api
commentLike.addEventListener("click", () => {
const addLike = commentData.id;
axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
console.log("Like has been added!");
likeCounter.textContent = Number(likeCounter.textContent)+1
});
});
Just add the line只需添加行
likeCounter.textContent = Number(likeCounter.textContent)+1
to the promise chain.到 promise 链。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.