如何独立调用show / hidefunction

嗨,我得到了帮助,最终我得到了jquery show / hidefunction,效果很好。 但是,当有几个评论小组时,我花了一整天的时间做下一步。

这里的代码

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(); }); }); Show Comments
This is #comment1
This is #comment2
Show Comments
This is #comment1
This is #comment2
Show Comments
This is #comment1
This is #comment2
Show Comments
This is #comment1
This is #comment2

有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一个显示。

rest随意玩这个演示,希望对此有所帮助。

 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(); }); });​ 

如果您希望a标签显示正确的文本 – 请使用以下代码:

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

(我接受了xdazz的回答并稍微改了一下,因为你不能使用1个变量(toogle)进行4个链接。)DEMO: http : //jsfiddle.net/jAMGE/

试试这个:

 var toggle = false; $(function() { $(document).on('click', 'a.comments', function(e) { e.preventDefault(); var $this = $(this); // $this.next().next() is the div after the link. $this.next().next().toggle(1000,function() { if(!toggle) { $this.text('Hide Comments'); toggle = !toggle; }else { $this.text('Show Comments'); toggle = !toggle; } }); }); }); 

DEMO