【问题标题】:How to fix foreach loop in function with many getElementsByClassName arguments如何使用许多 getElementsByClassName 参数修复函数中的 foreach 循环
【发布时间】:2021-11-19 17:34:33
【问题描述】:

由于commentValue 取[0],因此下面的函数仅适用于第一个帖子(左图)。 我尝试修复该功能,但仍然出现错误:注释未定义。

function AddComment(postId) {
    let commentValue = document.getElementsByClassName("thisIsTheComment")[0];
    var comment = commentValue.value;
    if (comment != null || comment.trim() != "") {
        var data = {
            PostId: postId,
            Comment: comment
        };
        var url = "https://localhost:44374/Comment/AddComment";
        axios.post(url, data)
            .then(function (response) {
                commentValue.value = "";
            })
            .catch(function (error) {
                console.log(error)
            })
    }
}

#第二次尝试:

function AddComment(postId) {
    let commentValues = document.getElementsByClassName("thisIsTheComment");
    for(var comment in commentValues) {
        var thecomment = comment.value;
        if (thecomment != null || thecomment.trim() != "") {
            var data = {
                PostId: postId,
                Comment: thecomment
            };
            var url = "https://localhost:44374/Comment/AddComment";
            axios.post(url, data)
                .then(function (response) {
                    thecomment.value = "";
                })
                .catch(function (error) {
                    console.log(error)
                })
        }
    }
}

这是 HTML:

<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)" ><i class="fas fa-paper-plane"></i></button>
</div>

我怎样才能修复这个功能,所以我可以为每个帖子写评论。

【问题讨论】:

  • OP 需要处理例如分别为每个评论字段的“单击”/“提交”事件。因此,一种方法是编写 ... document.querySelectorAll('.thisIsTheComment').forEach(elm =&gt; elm.addEventListener('click', AddComment)) ... 而 AddComment 需要更改为处理传递的 event 对象的 currentTarget 的值变化。
  • Abdullukh 指出了我犯的正确错误。但是,我必须找到一种不同的方法,因为 (if thecomment != '') 不存在。它会接受所有输入,即使它们是空的,也会发布它们。

标签: javascript asp.net-web-api


【解决方案1】:

你正在使用for in,其中元素是一个字符串

   for(var comment in commentValues) {
        var thecomment = comment.value;

使用for of

   for(var comment of commentValues) {
      var thecomment = comment.value;

【讨论】:

  • 如果解决了您的问题,请将答案标记为已接受(✓)
猜你喜欢
  • 2019-03-09
  • 1970-01-01
  • 2018-03-14
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多