2014-02-16 26 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