jQuery在3个div上切换 [英] Jquery toggle on 3 divs

查看:294
本文介绍了jQuery在3个div上切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有以下jQuery代码,当单击每个div时,它将对自己的相应div项进行动画处理,并关闭可能已经打开的任何其他div,但我敢肯定,有更好的方法对其进行编码和制作比我做的更紧凑.任何帮助将不胜感激.

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.

推荐答案

我总是通过在要单击的元素上添加一些额外的元数据(使用data-*属性)来解决此问题,以使其与内容相关联:

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>

注意,我也给了所有三个div相同的类,使我可以将相同的动作与所有三个div相关联.

Notice ive also given all three div's the same class, enabling me to associate the same action with all three.

然后jQuery变为:

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);

});

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

这篇关于jQuery在3个div上切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆