>我在评论区有一个名为"回复"的链接。单击链接时,将弹出一个评论框。如果我重新单击"回复"按钮,我希望它(以及所有其他评论框)消失。目前它不会消失,并不断打开更多评论框。
$('.replylink').click(function(event){ // Create comment box after clicking reply
event.stopPropagation();
var commentBox = $('<div class="comment-box"></div>');
$(this).closest('div').after(commentBox);
});
我用 toggle() 尝试了几件事,但如果我这样做
$($(this).closest('div').after(commentBox)).toggle();
例如,它将切换"回复"链接。因此,回复链接消失并出现评论框。我不明白如何只切换评论框。有谁可以帮助菜鸟?嗤!
下面的代码将打开一个.comment-box
(如果它对于单个线程确实存在),则将其删除。
我已经在您的.closest()
函数中添加了一个类,如果您只是寻找一个div
那么这是非常广泛的!如果你添加一个类,你会发现它要好得多 - 例如,你可以在回复链接和包装器之间添加多个div和包装器。您现在可能不需要这样做...但将来你可能会!这意味着您的代码更具前瞻性。
我已经注释了下面的代码。它将适用于单个页面上的多个线程/评论部分,但也适用于单个评论区域。
我还附加了评论框以.before()
回复链接而不是.after()
......从UI的角度来看,它感觉更自然,但显然是一种纯粹的风格变化。
演示
// Create comment box after clicking reply
$('.replylink').click(function(event) {
// Stop default action for click (i.e. going to top of page)
event.preventDefault();
// Set wrapping thread div
// this lets you have multiple threads on the same page (if needed)
thread = $(this).closest("div.thread");
// Check if thread has an opened comment box
if (thread.find(".comment-box").length > 0) {
// Delete any comment-box within this comment thread
thread.find(".comment-box").remove();
} else {
// Uncomment the line below if you want to close all other comment boxes
// $(".comment-box").remove();
// Create a coment box if it doesn't exist
var commentBox = $('<div class="comment-box"></div>');
$(this).before(commentBox);
}
});
.comment-box {
height: 20px;
padding: 10px;
border: 1px solid blue;
margin-bottom: 10px;
}
.thread {
border: 1px black solid;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thread">
<h3>Thread One</h3>
<a href="#" class="replylink">Reply</a>
</div>
<div class="thread">
<h3>Thread Two</h3>
<a href="#" class="replylink">Reply</a>
</div>
<div class="thread">
<h3>Thread Three</h3>
<a href="#" class="replylink">Reply</a>
</div>