Jquery在3个div上切换

HTML:

First Content

second Content

Third Content

JS:

  $("div.one").click (function(){ $("#bottomContent2").hide(); $("#bottomContent3").hide(); $("#bottomContent").animate({width: "toggle"}, 1000); }); $("div.two").click (function(){ $("#bottomContent").hide(); $("#bottomContent1").hide(); $("#bottomContent2").animate({width: "toggle"}, 1000); }); $("div.three").click (function(){ $("#bottomContent").hide(); $("#bottomContent2").hide(); $("#bottomContent3").animate({width: "toggle"}, 1000); }); 

我有以下jQuery代码,当单击每个div时,它将为其自己的相应div项设置动画并关闭可能已经打开的任何其他div但我相信有更好的方法来编码它并使其比我已经做好了。 任何帮助将不胜感激。

我总是通过在被点击的元素上添加一些额外的元数据(使用data-*属性)来关联它的内容来解决这个问题:

 
Click me for bottom content
Click me for bottom content 1
Click me for bottom content 2

注意我也给了所有三个div同一个类,使我能够将相同的动作与所有三个相关联。

然后jQuery变成:

 $("div.action").click (function(){ var $this = $(this); $('div.action').not($this).each(function(){ var $other = $(this); var otherTarget = $other.data('content'); $(otherTarget).hide(); }); var target = $this.data('content'); $(target).animate({width: "toggle"}, 1000); }); 

实例: http : //jsfiddle.net/rHKML/