2012-08-02 17 views
3

我有一個像如何獲得TD的對應日的標識表中的

<table> 
    <thead> 
     <tr> 
      <th id ="myid1">header1</th> 
      <th id ="myid2">headre "2</th> 
      <th id ="myid3">header3</th> 
     </tr> 
    </thead> 
     <tr> 
      <td>v1</td> 
      <td>v2</td> 
      <td>v3</td> 
     </tr> 
     <tr> 
      <td>v10</td> 
      <td>v11</td> 
      <td>v12</td>   
     </tr> 
     <tr> 
      <td>v20</td> 
      <td>v21</td> 
      <td>v22</td>      
     </tr> 
     <tr> 
      <td>v30</td> 
      <td>v31</td> 
      <td>v32</td>      
     </tr> 
</table> 

的情景可以有成千上萬行的。

我需要獲取該屬性所屬的td的id。例如

。如果我點擊第三行的第三TD ..我應該得到相應的次的ID,這裏是myid3(這裏的硬編碼,但它將爲基於從服務器端的值)

$('tbody td').live('click', function() { 
    var idOfTh = ?? 
});   

回答

3
$(function(){ 
    $('td').click(function() { 
     alert($('table th').eq($(this).index()).attr('id')); 
    }); 
}); 

工作的jsfiddle:http://jsfiddle.net/6etRb/

你只需要使用實時代表團如果被動態添加的錶行,並在這種情況下,如由他人描述你應該使用.on()

1

的以下的答案是錯的,但我是編輯,因爲它可以幫助別人

$('tbody td').live('click', function() { 
    var tdIndex = $(this).parent('tr').indexOf($(this)); 
    var idOfTh = $(this).parent('table').find('tr').eq(tdIndex); 
}); 

未經檢驗的,但理論上應該工作。

CORRECTION

上述不正確,如下面菲利克斯克林指出。獲得索引的正確方法是簡單地通過調用$(this).index()。我推測這將在匹配選擇器內找到$(this)的位置(在這種情況下,在<tbody>中每<td>),但實際上,如果您通過index()函數沒有參數,它會找到相對於其同級的索引。感謝Felix指出the relevant documentation

+1

這是不正確的。獲取像這樣的索引:'var tdIndex = $(this).index()'。另外,'.parent('table')'應該是'.closest('table')'('。parent('table')'不會選擇任何元素,因爲'td'的父節點不是'table'),'.find('tr')'應該是'.find('th')' 。 – 2012-08-02 14:20:43

+0

謝謝菲利克斯。但是不會在匹配選擇器中的所有** td元素中獲得td的索引,而不僅僅是該行嗎? – 2012-08-02 14:22:51

+1

不,它獲取其兄弟元素中的索引:*「如果沒有參數傳遞給'.index()'方法,則返回值是一個整數,指示jQuery對象中第一個元素相對於其同級元素的位置。「*(http://api.jquery.com/index/)。 – 2012-08-02 14:23:13

1

您可以使用eq()方法,請嘗試以下操作:

$('tbody td').live('click', function() { 
    var ind = $(this).index() 
    var idOfTh = $('thead th:eq('+ind+')').attr('id') 
}); 

請注意,live()已被棄用,你可以使用on()代替。

1

首先,.live()函數已被棄用。如果您想委派事件,請使用.on()(jQuery 1.7+)或.delegate()。我假設你在其餘的部分使用.on(),但是如果你必須使用.delegate(),那麼只有一個小的語法修改(切換前兩個參數)。

$(document).on('click', 'tbody td', function() { 
    var tdIndex = $(this).index(); 
    //^gets the index of the clicked element relative to its siblings 
    var thId = $('thead th:eq(' + tdIndex + ')')[0].id; 
    //^selects the th element in the same position in its row, then gets its id 
}); 
0

這裏有一個方法,你可以做到這一點:

$('td').click(function() { 
    var colNum = $(this).parent().children().index($(this)) + 1; 
    alert($('#myid' + colNum).text());  
});​ 

的jsfiddle:http://jsfiddle.net/p8SWW/4/

0

的處理程序可以看起來像:

function() { 
    var self = this 
    var th_num = 0; 

    $(this).parent().children().each(function(num){ 
     if (this == self) { 
      th_num = num; 
      return false 
     } 
    }); 

    var th_id = $('thead th').eq(th_num).attr('id'); 
}