gpt4 book ai didi

javascript - 使用标题元素 ID 的 jquery Accordion 选项卡索引

转载 作者:行者123 更新时间:2023-11-28 20:14:37 25 4
gpt4 key购买 nike

//html

<div id="accordion" >
<h3 class='headAcc' id="head_1">First header</h3>
<div>First content panel</div>
<h3 class='headAcc'id="head_2">Second header</h3>
<div>Second content panel</div>
</div>

//javascript

$('#accordion').accordion({collapsible:true,active:false});

问题:默认情况下所有选项卡都是关闭的。所以我需要使用标题元素 id 获取选项卡的索引。我怎样才能做到这一点。

我尝试过以下。但没有运气。提前致谢。

var indexOfheaderOne= $('h3#head_1').index(); //returns 0 which is ok
var indexOfheaderTwo= $('h3#head_2').index(); // returns 2 instead of 1.

//I think the reason is it will count the indexes based on all sibling elements
//not just from header elements. Is there any workaround for this.

编辑

对@Thusar解决方案进行少量修改

假设你的html包含更多<h3> Accordion 之外的元素。然后,以下解决方法将适用于这种类型的场景。

HTML

<h3 id="test1">Example Head 1</h3> 
<h3 id="test2">Example Head 2</h3>
<h3 id="test3">Example Head 3</h3>

<div id="accordion" >
<h3 class='headAcc' id="head_1">First header</h3>
<div>First content panel</div>
<h3 class='headAcc'id="head_2">Second header</h3>
<div>Second content panel</div>
</div>

JavaScript

alert($('h3#head_1').index('h3.headAcc'));//return 0 as expected
alert($('h3#head_2').index());//return 2 because element is in after first tab div
alert($('h3#head_2').index('h3.headAcc'));//return 1 as expected

最佳答案

DEMO

var indexOfheaderTwo= $('h3#head_2').index('h3'); //returns 1 as index of h3 with respect to parent is traced and it is the 2nd child of parent with tag h3.

索引从0开始。

问题的解释。

var indexOfheaderOne= $('h3#head_1').index(); //returns 0 As it is first child of parent div

var indexOfheaderTwo= $('h3#head_2').index(); // returns 2 As it is third child of parent div

阅读.index()

关于javascript - 使用标题元素 ID 的 jquery Accordion 选项卡索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com