HTML:
<div id="bottomContent" class="bottom_content" > <p>First Content</p> </div>
<div id="bottomContent2" class="bottom_content" > <p>second Content</p> </div>
<div id="bottomContent3" class="bottom_content" > <p>Third Content</p> </div>
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
我有以下jQuery代码,当单击每个div时,它将为其自己的相应div项设置动画并关闭可能已经打开的任何其他div但我相信有更好的方法来编码它并使其比我已经做好了.任何帮助将不胜感激.
我总是通过在data-*被点击的元素上添加一些额外的元数据(使用属性)来关联它的内容来解决这个问题:
<div class="action" data-content="#bottomContent">
Click me for bottom content
</div>
<div class="action" data-content="#bottomContent1">
Click me for bottom content 1
</div>
<div class="action" data-content="#bottomContent2">
Click me for bottom content 2
</div>
Run Code Online (Sandbox Code Playgroud)
注意我也给了所有三个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);
});
Run Code Online (Sandbox Code Playgroud)