Jquery toggle on 3 divs

旧城冷巷雨未停 提交于 2019-12-12 05:05:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!