2013-10-16 61 views
0

// HTMLjquery的手風琴標籤索引使用頭部元素ID

<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> 

// java描述

$('#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>元素。然後,以下解決方法將適用於該類型的場景。

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 

回答

2

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()

+1

真棒兄弟。這就是我想要的。 – Viraths

+0

@Viraths歡迎:) :)高興地幫助:) –

1

你爲什麼它返回2假設是正確的。

更改您的索引選擇到如下:

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

的jsfiddle:http://jsfiddle.net/GxQ3c/2/

+0

感謝兄弟。我知道了。 – Viraths

0
$("#accordion").accordion("option", "active", i); 

你試試這個?用手風琴它可能是內置功能。

試用演示this