2012-04-05 77 views
1

點擊孩子時,我想知道父母的索引號。例如,當我點擊每個ul的孩子時,有一個3 ul的div,它應該顯示父索引號。它的父母。我怎樣才能得到這個?我如何找到父母點擊孩子的索引

的jQuery:

$('.opSection').on('click','li',function(){ 

    var num = $(this).parent('ul').index(); 

    alert(num); 

    //alert(chartData.Indices[$(this).index()][$(this).index()]); 

    }) 

HTML:

<div class="opSection">//parent of all 
<dl><dd> 
     <ul class="selectGroup" title='allIndia' data-select='1'> 
      <li data-index="123" class="c_on">All India</li> // when i click any of li i need 0 
     </ul> 

     <ul class="selectGroup" title='allIndia' data-select='1'> 
      <li data-index="123" class="c_on">All India</li> // when i click this, i need 1 
     </ul> 
</dd></dl> 
    </div> 

回答

3
$('.opSection').on('click', 'li', function() { 
    alert($(this).parent().index(); 
}); 

注意我用事件處理委託多個元素事件時提高性能。

這裏的重要部分是parent()來選擇ul,然後index(),當不帶參數傳遞時,返回它的位置相對於它的兄弟元素。

編輯正如您在您的評論已經說您的標記並不像你在問題發佈什麼是相同的,而不是嘗試以下操作:

$('.opSection').on('click', 'li', function (e) { 
    $(e.delegateTarget).find('.selectGroup').index(this.parentNode); 
}); 

$(e.delegateTarget)是相同的(但速度更快)比$('.opSection')。然後,我們搜索所有​​的所有後代(find()),並使用相同的index()方法找到我們點擊的位置。

+0

它總是隻給0。 UL並非('.opSection')的直接子女,它沒有孩子,其中一個孩子是UL – 3gwebtrain 2012-04-05 13:25:29

+0

@ 3gwebtrain:請參閱我的編輯。 – Matt 2012-04-05 13:34:17