gpt4 book ai didi

jquery - 如何独立调用显示/隐藏函数

转载 作者:行者123 更新时间:2023-12-01 03:19:29 24 4
gpt4 key购买 nike

嗨,我得到了帮助,最终我得到了运行良好的 jquery 显示/隐藏功能。但我花了一整天的时间来进行下一步,让其在有多个评论组的情况下发挥作用。

代码在这里

var toggle = false;
$(function() {
$(document).on('click', 'a.comments', function(e) {
var $this = $(this);
$('.toggleComments').toggle(1000,function() {
if(!toggle) {
$this.text('Hide Comments');
toggle = !toggle;
}else {
$this.text('Show Comments');
toggle = !toggle;
}
});
e.preventDefault();
});
});

<a href="#" class="comments">Show Comments</a><br />
<div class="toggleComments" style="display:none;">This is #comment1 <br />This is #comment2 <br /></div>
<a href="#" class="comments">Show Comments</a><br />
<div class="toggleComments" style="display:none;">This is #comment1 <br />This is #comment2 <br /></div>
<a href="#" class="comments">Show Comments</a><br />
<div class="toggleComments" style="display:none;">This is #comment1 <br />This is #comment2 <br /></div>
<a href="#" class="comments">Show Comments</a><br />
<div class="toggleComments" style="display:none;">This is #comment1 <br />This is #comment2 <br /></div>

有 4 个评论组,但由于 html DOM 相同,因此单击每个评论组时它们无法独立工作。

您能否建议如何处理这种情况,独立管理它们的显示/隐藏,而无需为每个评论组分配 jquery 脚本?

最佳答案

工作演示 http://jsfiddle.net/ZXNWF/ http://jsfiddle.net/X5ZUU/1/或更改文本:http://jsfiddle.net/Xam9q/

API:http://api.jquery.com/nextAll/

然后使用 nextAll 始终显示 :first 一个。

休息一下,随意玩一下演示,希望这对您有所帮助。

代码

var toggle = false;
$(function() {

$(document).on('click', 'a.comments', function(e) {
$('.toggleComments').hide();
var $this = $(this);
$(this).nextAll('.toggleComments:first').toggle(1000,function() {
if(!toggle) {
$this.text('Hide Comments');
toggle = !toggle;
}else {
$this.text('Show Comments');
toggle = !toggle;
}
});
e.preventDefault();
});
});

简单

var toggle = false;
$(function() {

$(document).on('click', 'a.comments', function(e) {
$('.toggleComments').hide();
var $this = $(this);
$('.comments').text('Show Comments');
$this.text('Hide Comments');
$(this).nextAll('.toggleComments:first').toggle(1000,function() {
});
e.preventDefault();
});
});

关于jquery - 如何独立调用显示/隐藏函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11490310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com