问题
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>
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);
});
I have the following jQuery code whereby when each of the divs is clicked, it will animate its own corresponding div item and close any other div that may be already opened but I am sure there are better ways to code it and make it more compact than I have done. Any help will be appreciated.
回答1:
I always approach this problem by putting some extra metadata (using data-*
attributes) on the element being clicked to associated it's content:
<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>
Notice ive also given all three div's the same class, enabling me to associate the same action with all three.
Then the jQuery becomes:
$("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);
});
Live example: http://jsfiddle.net/rHKML/
来源:https://stackoverflow.com/questions/10598952/jquery-toggle-on-3-divs