【问题标题】:jquery Accordion - how to open the second tab by default on page loadingjquery Accordion - 如何在页面加载时默认打开第二个选项卡
【发布时间】:2013-09-25 14:54:46
【问题描述】:

我是 jquery 和 javascript 的绝对菜鸟,实际上我只是使用我在网上找到的简单代码。 这会创建一个手风琴列表,但我想在页面加载时打开第二个选项卡(或第一个选项卡以外的任何选项卡)。 然后,当单击任何其他选项卡时,默认打开的选项卡应该关闭。

这是我正在使用的代码:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>

<style>
    .accord-content { display: none; }
</style>
</head>

<body>
    <div class="accordion">
    <div class="accord-header">Header 1</div>
    <div class="accord-content">This is the content for the first header.</div>
    <div class="accord-header">Header 2</div>
    <div class="accord-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
    </div>

</body>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $(".accordion .accord-header").click(function() {
    if($(this).next("div").is(":visible")){
    $(this).next("div").slideUp("slow");
    } else {
    $(".accordion .accord-content").slideUp("slow");
    $(this).next("div").slideToggle("slow");
    }
    });
    });
    </script>
</html>

我怎样才能做到这一点? 越简单越好。

提前谢谢大家。

【问题讨论】:

    标签: javascript jquery list accordion jquery-tabs


    【解决方案1】:

    更优雅的方式:

    $( ".selector" ).accordion({ active: 1 });
    

    请记住,活动属性是零索引的。 0 代表第一个选项卡。 1 代表第二个。

    JQuery doc's are excellent

    【讨论】:

    • 按照这个思路,您可以简单地将“data-slide=1”添加到 html 元素,然后执行以下操作: $(".selector").each( function(i, item) { $(this).accordion({ active: parseInt($(this).attr('data-slide'),10) }); });
    • collapsible: true 的语法是什么?
    • @Andrew 你为什么要这么做。看看你的示例代码有多可怕。
    【解决方案2】:

    您可以使用.trigger() 模拟对所需选项卡的点击。 这是working fiddle

    在您的 jquery 上,在 document.ready 结束之前:

    $(".accordion .accord-header:eq(1)").trigger('click');
    

    所以你的最终 JS :

    $(document).ready(function() {
        $(".accordion .accord-header").click(function() {
            if($(this).next("div").is(":visible")){
                $(this).next("div").slideUp("slow");
            } else {
                $(".accordion .accord-content").slideUp("slow");
                $(this).next("div").slideToggle("slow");
            }
        });
        $(".accordion .accord-header:eq(1)").trigger('click');
    });
    

    【讨论】:

    • 非常感谢。如果我需要在手风琴中插入另一个选项(标题 3、4、5 等)怎么办?
    • 嗨,你可以添加 html 代码 =) 看看这个更新的小提琴:jsfiddle.net/ngGqA/7
    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多