【问题标题】:Super simple jQuery tabs - without UI - collapse on page load超级简单的 jQuery 选项卡 - 没有 UI - 在页面加载时折叠
【发布时间】:2016-05-13 14:20:45
【问题描述】:

我希望在页面加载时折叠所有标签。现在第一个默认打开:

  $(document).ready(function($) {
    $('#forms').find('.forms-toggle').click(function(){

      //Expand or collapse this panel
      $(this).next().slideToggle('fast');

      //Hide the other panels
      $(".forms-content").not($(this).next()).slideUp('fast');

    });
  });

HTML 和 CSS 在这里:

https://jsfiddle.net/re8x8cx3/

【问题讨论】:

    标签: javascript jquery tabs accordion


    【解决方案1】:

    把这个放在 dom 中准备好,

     $(".forms-content").hide();
    

    那么代码就是,

    $(document).ready(function($) {
      $(".forms-content").hide();
      $('#forms').find('.forms-toggle').click(function() {
        //Expand or collapse this panel
        $(this).next().slideToggle('fast');
        //Hide the other panels
        $(".forms-content").not($(this).next()).slideUp('fast');
      });
    });
    

    Fiddle

    【讨论】:

      【解决方案2】:

      还请改进你的JS:

      (function($){
          //store reusable global vars
          var $forms = $('#forms'),
              $formContents = $forms.find(".forms-content");
      
          //hide on load
          $formContents.hide();
      
          //attach only on handler to #forms instead of to every tab separately
          $forms.on('click', '.forms-toggle', function(event){
              event.preventDefault();
      
              //reuse this value (only on reference)
              var $thisContent = $(this).next(),
      
              //Expand or collapse this panel
              $thisContent.slideToggle('fast');
      
              //Hide the other panels
              $formContents.not($thisContent).slideUp('fast');
          });
      });
      

      【讨论】:

      • 您能解释一下您的代码如何更好吗?谢谢
      • 速度更快,因为它重用了搜索结果(使查询成为整个 DOM 结构中的搜索),更易于维护。如果你有很多选项卡,那么函数处理程序就会更少:假设在一页上你有 20 个选项卡的表单。您的代码生成 20 个事件处理程序,main 创建 1 个。您使用了两次 $(this).next(),这违反了 DRY 编码标准,使您的代码更难维护。与$(".forms-content") 相同 - 添加在答案中
      • 谢谢。不幸的是,您的代码对我不起作用。
      • 您遇到了什么问题?你能提供HTML吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多