我有一个页面有多个评论部分。请看这里:http://bluepresley.com/tna/question/where-is-the-best-soup-curry-in-sapporo/
这是一个问答网站,正如您在页面上看到的那样,问题以及每个答案都有一个灰色的“写回复...”框。
我想默认隐藏它们,只有当有人点击生成的“显示评论”按钮时才会显示它们。这是我正在使用的代码:
// Show/Hide Comments
jQuery(document).ready(function() {
// Get #comment-section div
var commentsDiv = jQuery('.dwqa-comments');
// Only do this work if that div isn't empty
if (commentsDiv.length) {
// Hide #comment-section div by default
jQuery(commentsDiv).hide();
// Append a link to show/hide
jQuery('<button/>')
.attr('class', 'toggle-comments')
.attr('href', '#')
.html('Show Comments ')
.insertBefore(commentsDiv);
// Encase button in #toggle-comments-container div
jQuery('.toggle-comments').wrap(jQuery('<div/>', {
id: 'toggle-comments-container'
}));
// When show/hide is clicked
jQuery('.toggle-comments').on('click', function(e) {
e.preventDefault();
console.log(jQuery(this).next('.dwqa-comments'));
// Show/hide the div using jQuery's toggle()
jQuery(this).next('.dwqa-comments').toggle('slow', function() {
// change the text of the anchor
//var anchor = jQuery('.toggle-comments');
//var anchorText = anchor.html() == 'Show Comments ' ? 'Hide Comments ' : 'Show Comments ';
//jQuery(anchor).html(anchorText);
});
});
} // End of commentsDiv.length
}); // End of Show/Hide Comments
我正在使用.next()
方法尝试使用this
来定位dwqa-comments的下一个元素,正如我在许多教程中看到的那样,但我不知道为什么它不起作用
思想?
答案 0 :(得分:1)
问题是.next(),因为评论是被点击元素的父级的下一个兄弟。
同样toggle-comments-container
应该是一个类,因为页面中可以有多个元素,而id必须是唯一的
所以试试
// Show/Hide Comments
jQuery(function ($) {
// Get #comment-section div
//added the has() clause so that only comments with actual comment elements are targeted
var commentsDiv = $('.dwqa-comments').has('.comment');
// Only do this work if that div isn't empty
if (commentsDiv.length) {
// Hide #comment-section div by default
$(commentsDiv).hide();
// Append a link to show/hide
$('<button/>')
.attr('class', 'toggle-comments')
.attr('href', '#')
.html('Show Comments ')
.insertBefore(commentsDiv);
// Encase button in #toggle-comments-container div
$('.toggle-comments').wrap($('<div/>', {
//use class because id of an element must be unique
class: 'toggle-comments-container'
}));
// When show/hide is clicked
$('.toggle-comments').on('click', function (e) {
e.preventDefault();
console.log($(this).next('.dwqa-comments'));
// Show/hide the div using $'s toggle()
//need to access the parent because the `dwqa-comments` element is the next sibling of the clicked `toggle-comments`'s parent
$(this).parent().next('.dwqa-comments').toggle('slow', function () {
// change the text of the anchor
//var anchor = $('.toggle-comments');
//var anchorText = anchor.html() == 'Show Comments ' ? 'Hide Comments ' : 'Show Comments ';
//$(anchor).html(anchorText);
});
});
} // End of commentsDiv.length
}); // End of Show/Hide Comments