【发布时间】: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 => elm.addEventListener('click', AddComment))... 而AddComment需要更改为处理传递的event对象的currentTarget的值变化。 -
Abdullukh 指出了我犯的正确错误。但是,我必须找到一种不同的方法,因为 (if thecomment != '') 不存在。它会接受所有输入,即使它们是空的,也会发布它们。
标签: javascript asp.net-web-api