0

我的目标是附加按钮以隐藏对评论的回复,如果每个评论都没有回复,则不显示此按钮。

请不要因为这段代码而责备我,因为我是新手并且努力学习。

这是代码:

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";
}

所以,现在我不知道如何循环浏览所有评论并在没有回复时隐藏“隐藏回复”按钮。

希望帮助用普通的Javascript解决这个问题。提前致谢!

4

1 回答 1

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();

演示:小提琴

于 2013-07-29T10:59:15.660 回答