我的目标是添加按钮以隐藏对评论的回复,如果每条评论都没有回复,则不显示此按钮。
请不要因为我是新手并且努力学习而责备我这个代码。
以下是代码:
var replies = document.querySelectorAll(".comments_list > .comment_item > .reply_comments"); //should check if .childNodes.length === 1
var comments = document.querySelectorAll(".comments_list > .comment_item");
var combodys = document.querySelectorAll(".comments_list > .comment_item > .comment_body");
addBtn();
function addBtn() {
for (var i = 0; i < comments.length; i++) {
var combody = combodys[i];
var btn = document.createElement("input");
btn.type = "button";
btn.className = "hidereplies";
btn.value = "show replies";
combody.appendChild(btn); //don't show if replies.childNodes.length === 1
}
}
添加按钮后,我想在回复块为空时检查注释是否包含回复和隐藏按钮。试图检查childNodes方法并面临我必须“+1”到当前“hidereplies”按钮值的问题:
if (replies[6 + 1].childNodes.length === 1) {
document.querySelectorAll(".hidereplies")[6].style.display = "none";
}
所以,现在我不知道如果没有回复,如何循环浏览所有评论并隐藏“hidereplies”按钮。
希望在普通的Javascript中帮助解决这个问题。 提前谢谢!
答案 0 :(得分:1)
尝试
function getChildrenByClassName(el, className){
var children = [];
for (var i = 0; i < el.childNodes.length; i++) {
if (el.childNodes[i].className == className) {
children.push(el.childNodes[i]);
}
}
return children;
}
function addBtn() {
var comments = document.querySelectorAll(".comments_list > .comment_item"), comment, combody;
for (var i = 0; i < comments.length; i++) {
comment = comments[i];
var replies = comment.querySelectorAll('.reply_comments .comment_body');
if(replies.length > 0){
combody = getChildrenByClassName(comment, 'comment_body')[0];
if(combody){
var btn = document.createElement("input");
btn.type = "button";
btn.className = "hidereplies";
btn.value = "show replies";
combody.appendChild(btn); //don't show if replies.childNodes.length === 1
}
}
}
}
addBtn();
演示:Fiddle