简体   繁体   中英

JQuery UI (accordion), open active tab on initialisation

I have a basic sidenav menu on a site, this has parent items and child items according to the h3 > div structure recommended by JQuery's documentation.

I need to open the "active" tab based on the page that it's on. The CMS already applies an "active" class to the h3 but the only way I've successfully been able to open (or activate) the tab has been to use the h3's index ie 0,1,2,3. With me being a novice I've struggled to get the index of the "active" h3 because most of the tutorials show examples of getting the index of a li element within an ordered list.

My html looks like this:

<div id="accordion">
    <h3>Menu 1</h3>
    <div>sub-menu</div>
    <h3>Menu 2</h3>
    <div>sub-menu</div>
    <h3 class="active">Menu 3</h3>
    <div>sub-menu</div>
    <h3>Menu 4</h3>
    <div>sub-menu</div>
</div>

Now I know that the 3rd h3 is index 2 so if I needed to hardcode that tab to be open it would be easy but I need to get the index based on which h3 element (there isn't a fixed amount ever) has the "active" class.

The CMS is OpenCart and the JQuery version is 1.10.1

Reading your question, you shouldn't need to know the index to open it depending on the page. Just target the H3 that is active using a css selector in jQuery, then perform the needed action on it, like below;

$('.accordion h3.active').slideDown(); 

Example code, you'd probably need to use .next() to open the submenu, eg;

 $('.accordion h3.active').next().slideDown();

如果出于任何原因要查找活动h3的索引,仍可以使用以下代码

$("#accordion h3.active").index()/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM