1

我想在按钮单击时显示/隐藏带有子项的 div,而不是在不同的父块中显示/隐藏其他相同的 div。对不起我不好的解释和js知识,也许代码可以说得更好:

for (a = 0; a < document.querySelectorAll("#hidereplies").length; a++) {
    var btn = document.querySelectorAll("#hidereplies")[a];
    btn.onclick = function () {
        for (var y = 0; y < document.querySelectorAll(".reply_comments").length; y++) {
            var reply = document.querySelectorAll(".reply_comments")[y];
            reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
        }
    };
}

jsfiddle 上的演示

4

1 回答 1

0

你做错了几件事。

首先,在您的 HTML 中,不要多次使用 ID。您已为按钮指定了相同的 ID。

接下来,将您的 querySelector 结果分配给一个数组并迭代该数组。

第三,您需要确定查询范围。您正在检查元素上的document所有内容,而不是被限制在当前 div 中。

//note that I've changed from an ID to a class for your buttons
var buttons = document.querySelectorAll(".hidereplies");

for (a = 0; a < buttons.length; a++) {
    var btn = buttons[a];
    btn.onclick = function (event) {
        var btn = event.currentTarget; //get the current button clicked
        var comments = btn.parentNode.querySelectorAll(".reply_comments"); //scope the search
        for (var y = 0; y < comments.length; y++) {
            var reply = comments[y];
            reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
        }
    };
}

HTML

<div class="comments_list">
    <div class="comment_item">
        <div class="comment_body">test1 - comments</div>
        <input type="button" class="hidereplies" value="show replies" />
        <div class="reply_comments">
            <div class="comment_body">want to hide only current ".reply_comments"</div>
        </div>
    </div>
    <div class="comment_item">
        <div class="comment_body">test2 - comments</div>
        <input type="button" class="hidereplies" value="show replies" />
        <div class="reply_comments">
            <div class="comment_body">but not all</div>
        </div>
    </div>
    <div class="comment_item">
        <div class="comment_body">test3 - no comments</div>
        <div class="reply_comments"></div>
    </div>
</div>

您更新的小提琴 - http://jsfiddle.net/yhtKa/4/

于 2013-07-30T17:36:30.380 回答