Javascript 选择相关TD的第TH行
如何检索所选td第TH行中的文本 是的,我找到了一些相关的帖子,但是没有什么能帮到我 我试过:Javascript 选择相关TD的第TH行,javascript,jquery,html,Javascript,Jquery,Html,如何检索所选td第TH行中的文本 是的,我找到了一些相关的帖子,但是没有什么能帮到我 我试过: $(document).on("click", "#sTab td,#pvTab td", function () { alert($('#sTab tr').find('th:nth-child(' + $(this).parent().index() + ')').innerHTML); alert($(this).parent()); var th = $(this).closest('ta
$(document).on("click", "#sTab td,#pvTab td", function () {
alert($('#sTab tr').find('th:nth-child(' + $(this).parent().index() + ')').innerHTML);
alert($(this).parent());
var th = $(this).closest('table').find('th').eq( this.cellIndex );
alert(th.innerHTML);
}
这应该起作用:
var index = $(this).index();
console.log($(this).parents("table").find("th:eq(" + index + ")").text());
编辑:行标题:console.log($(this.closest(“tr”).find(“th”).text())代码>
小提琴:这应该可以:
var index = $(this).index();
console.log($(this).parents("table").find("th:eq(" + index + ")").text());
编辑:行标题:console.log($(this.closest(“tr”).find(“th”).text())代码>
小提琴:我建议:
/* binds a click-handler to the 'tbody' element,
filters those clicks to only those that originate on a 'td' element:
*/
$('tbody').on('click', 'td', function(){
/* gets the siblings of the clicked 'td' element, filters those siblings
for 'th' elements, gets the first of those matching elements,
and then retrieves the text of that element, assigning it to the variable:
*/
var thText = $(this).siblings('th').first().text();
console.log(thText);
});
或者,使用更多的DOM(一个微小的效率提升):
参考资料:
我建议:
/* binds a click-handler to the 'tbody' element,
filters those clicks to only those that originate on a 'td' element:
*/
$('tbody').on('click', 'td', function(){
/* gets the siblings of the clicked 'td' element, filters those siblings
for 'th' elements, gets the first of those matching elements,
and then retrieves the text of that element, assigning it to the variable:
*/
var thText = $(this).siblings('th').first().text();
console.log(thText);
});
或者,使用更多的DOM(一个微小的效率提升):
参考资料:
你离得不远。这适用于您的示例:
$(document).on("click", "#sTab td,#pvTab td", function () {
var tdIndex = $(this).index(),
table = $(this).closest('table'),
headingIndex = tdIndex + 1,
thText = table.find('th:nth-child(' + headingIndex + ')').text();
alert(thText);
});
你离得不远。这适用于您的示例:
$(document).on("click", "#sTab td,#pvTab td", function () {
var tdIndex = $(this).index(),
table = $(this).closest('table'),
headingIndex = tdIndex + 1,
thText = table.find('th:nth-child(' + headingIndex + ')').text();
alert(thText);
});
编辑:解释-行始终是单元格的父行,因此无需查找索引-只需在有单元格的行中查找标题即可
编辑:解释-行始终是单元格的父行,因此无需查找索引-只需在有单元格的行中查找标题即可
SyntaxError:missing)位于参数列表之后。警报($(this).closest('tr').find('th').text())代码>这是一个过于复杂的演示。您想单击一个td
(任意td
?)并从单击行开头的th
中检索文本吗?是,任意td,是。为什么第一行不在thead中?整洁的按钮在小提琴上也能创造奇迹。您可以通过监听tr上的单击并在参数列表后查找th.SyntaxError:missing)来简化它代码>这是一个过于复杂的演示。您想单击一个td
(任意td
?)并从单击行开头的th
中检索文本吗?是,任意td,是。为什么第一行不在thead中?整洁的按钮在小提琴上也能创造奇迹。你可以通过点击tr并找到th来简化它。当然,我会在答案中添加解释(在代码注释中)。当然,我会在答案中添加解释(在代码注释中)。