你做错了几件事。
首先,在您的 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/