【问题标题】:jQuery toggle on/off between multiple divsjQuery 在多个 div 之间切换开/关
【发布时间】:2013-12-29 06:19:35
【问题描述】:

我在这里有一个非常简单的 jQuery 切换开关:http://jsfiddle.net/yVa3U/1/ - 但我不知道如何在单击下一个 div 时关闭活动 div。

关于如何做到这一点的任何建议?

谢谢

$(document).ready(function() {

  $('.answer').hide();

  $(".toggle").click(function(){

      $("div[rel='profile_" + $(this).attr("profile") + "']").toggle(400);
});

});​

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你应该添加

    $(".answer").not($(this).next()).hide(400);
    

    在调用toggle() 函数之前

    旁注

    1. 您可以将$("div[rel='profile_" + $(this).attr("profile") + "']").toggle(400); 行更改为 $(this).next().toggle(400);
    2. 最好使用data 属性,而不是使用profile 属性

    Demo

    【讨论】:

      【解决方案2】:

      你需要hideall答案点击exceptcurrent答案,你可以这样做,

      Live Demo

      $(document).ready(function() {
          $('.answer').hide();
          $(".toggle").click(function() {
              currentAnswerDiv = $("div[rel='profile_" + $(this).attr("profile") + "']");
              $('.answer').not(currentAnswerDiv).hide();
              currentAnswerDiv.toggle(400);
          });
      });​
      

      【讨论】:

      • 如果两次单击相同的切换元素,则不会切换活动答案
      【解决方案3】:

      你可以使用next()

      $(".toggle").click(function() {
             var $next=$(this).next().toggle(400)
            $('.answer').not($next).hide();  
      });
      

      最好用 CSS 隐藏你的答案类,而不是在 javascript 中等待就绪事件

      演示:http://jsfiddle.net/yVa3U/7/

      API 参考:http://api.jquery.com/next/

      【讨论】: