2014-02-16 28 views

回答

0

Fiddle Demo

$('tbody').on('click', 'td', function() { 
    var thText = $(this).closest('tbody').prev().find('th').first().text(); 
    console.log(thText); 
}); 


table體被容納在 tbody和標題標籤在 thead

你需要找到td的最接近tbody,比以前獲得標籤thead比找到th


.closest()

.prev()

.find()


Fiddle Demo

$('tbody').on('click', 'td', function() { 
    var index = $(this).index(); 
    var thText = $(this).closest('tbody').prev().find('th').eq(index).text(); 
    console.log(thText); 
}); 

.index()

.eq()

this keyword

+0

你能解釋一下代碼圖莎爾 – user3315887

+0

@ user3315887是的,我更新的答案只是等待一段時間 –

+0

有很多方法鏈的,所以我想什麼呢$(本).closest(「TBODY」)不然後又是什麼.prev()。find('th')。first()do? – user3315887

0

使用色譜柱來匹配理論值的索引。

$('tbody').on('click', 'td', function(){ 
    var thText = $(target).find("th").eq($(this).index()).text(); 
    console.log(thText); 
}); 
+0

這是做什麼eq($(this).index())?什麼是$(這)在這裏? – user3315887

+0

還有什麼是$(目標)? – user3315887

+0

$(this)是被點擊的td,在像eq(1)這樣的元素列表中抓取位置1中的那個,就像數組一樣。 – Wilmer