You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复含多getElementsByClassName参数函数的forEach循环 实现多帖子评论提交

问题原因梳理

第一个版本问题

document.getElementsByClassName("thisIsTheComment")[0] 固定取页面第一个匹配的评论输入框,所以无论点击哪个帖子的提交按钮,都只会读取第一篇帖子的评论内容,无法适配多帖子场景。

第二个版本问题

  • for...in 遍历getElementsByClassName返回的HTMLCollection对象时,拿到的comment是索引值而非DOM元素,调用comment.value自然会触发thecomment is undefined报错
  • 遍历所有评论输入框的逻辑不符合业务需求:点击单个帖子的提交按钮,仅需要提交当前对应帖子的评论,不需要批量提交所有帖子的评论

修复方案

第一步:修改HTML的点击事件传参

给AddComment新增一个参数,传入当前被点击的按钮DOM对象:

<div class="comment-form">
     <input type="text" name="theComment" class="thisIsTheComment comment-input" placeholder="Add a comment..." required/>
     <button type="submit" class="btnaddcomment color" id="btn_comment" onclick="AddComment(@post.Id, this)" ><i class="fas fa-paper-plane"></i></button>
</div>

第二步:修改JS函数逻辑

通过被点击的按钮找到同层级的评论输入框,仅读取当前对应输入框的内容:

function AddComment(postId, submitBtn) {
    // 找到按钮的父级容器,再查找当前容器下的评论输入框
    const commentInput = submitBtn.parentElement.querySelector('.thisIsTheComment');
    const comment = commentInput.value.trim();
    // 空值拦截用&&逻辑,避免空评论提交
    if (comment != null && comment !== "") {
        const data = {
            PostId: postId,
            Comment: comment
        };
        const url = "https://localhost:44374/Comment/AddComment";
        axios.post(url, data)
            .then(function (response) {
                // 提交成功后清空当前输入框内容
                commentInput.value = "";
            })
            .catch(function (error) {
                console.log(error)
            })
    }
}

逻辑说明

通过DOM节点的相对位置查找对应输入框,不需要全局遍历所有评论输入框,也不会出现下标固定取第一个的问题,每一个提交按钮只会和自己同容器的输入框绑定,完美适配多帖子场景。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 06:24:00