jquery Accordion - 如何在页面加载时默认打开第二个选项卡

Jac*_*pot 3 javascript jquery list accordion jquery-tabs

我是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>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?最简单,更好.

谢谢大家提前.

sur*_*190 16

更优雅的方式:

$( ".selector" ).accordion({ active: 1 });
Run Code Online (Sandbox Code Playgroud)

请记住,活动属性为零索引.0表示第一个选项卡.1代表第二个.

JQuery doc非常棒


Gui*_*zee 8

You can use the .trigger() to simulate a click on the desired tab. This is a working fiddle.

On your jquery, before the end of the document.ready :

$(".accordion .accord-header:eq(1)").trigger('click');
Run Code Online (Sandbox Code Playgroud)

So your final 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');
});
Run Code Online (Sandbox Code Playgroud)