使用& # 39;这个# 39;查找表头中的最后一行

Using 'this' to find the final row in a table header

本文关键字:最后 一行 表头 这个 查找 使用      更新时间:2023-09-26

我使用stupidtable (http://joequery.github.io/Stupid-Table-Plugin/)添加排序表。我使用回调来添加适当的向上或向下箭头,以显示用于排序的列以及它是升序还是降序。

原始事件处理程序使用代码:

table.bind('aftertablesort', function (event, data) {
    // data.column - the index of the column sorted after a click
    // data.direction - the sorting direction (either asc or desc)
    var th = $(this).find("th");
    th.find(".arrow").remove();
    var arrow = data.direction === "asc" ? "↑" : "↓";
    th.eq(data.column).append('<span class="arrow">' + arrow +'</span>');
});

这在只有一行标题的情况下工作得很好,但是如果有多行,它就不能,因为它发现第一行标题而不是最后一行。

我正在努力找出如何找到底部一行,以下另一个线程我尝试:

var th = $(this + ' thead tr:last').find("th");

但是这给出了一个语法错误,我猜是因为我没有正确使用'this'。有人能帮忙吗?

谢谢,

你不能把一个对象和一个字符串组合在一起来构建一个选择器。试试这个:

var th = $(this).find('thead tr:last').find("th");

this不是字符串,而是一个DOM元素。

你可以像这样使用它作为上下文选择器:

var th = $('thead tr:last', this).find("th");

但是.find比上下文更快,所以使用这个:

var th = $(this).find("thead tr:last th");

如果this引用你的表,你应该使用find

var th = $(this).find('thead tr:last')

下一行

$(this + ' thead tr:last')

将不起作用,因为this是一个对象,而您正在与字符串混合,这将导致

$("[object HTMLTableElement] thead tr:last")

您知道thead是用于表的标题部分。当问"bottom row"时你确定它是header还是body?

查找this为父节点的最后一行。

var last_header_row = $(this).find("thead").last("tr");

如果this是父节点,则在body中查找最后一行。

var last_body_row = $(this).find("tbody").last("tr");

注意,this引用是在事件回调函数的上下文中。如果不知道上下文是什么,我们就不能保证它是一个DOM元素引用。

如果你有一个来自表内的引用,其中thistr或其他东西。将对find(..)的调用替换为closest(..)