繁体   English   中英

如何使用 JS vanilla 仅刷新一个 DOM 元素

[英]How to refresh just one DOM element using JS vanilla

我正在使用 DOM 为我创建一个元素,显示特定评论收到的点赞数量。 当有人喜欢数据被推送到 API 的按钮时。 但是,为了看到喜欢的数量增加,我必须手动重新加载页面。

有没有办法自动刷新那个特定的 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!");
        });
    });

这里是 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
    });
});

只需添加行

likeCounter.textContent = Number(likeCounter.textContent)+1

到 promise 链。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM