如何在 jQuery 中选择第 n 个 HTML 行

How to select the nth HTML row in jQuery

本文关键字:HTML 选择 jQuery      更新时间:2023-09-26

我需要选择HTML表的第n行,只知道所选行的id。这是我的情况:JSFiddle 演示

<table class="mytable1">
    <tr><td id="12">1.0</td></tr>
    <tr><td id="20">1.1</td></tr>
    <tr><td id="120">1.2</td></tr>
    <tr><td id="260">1.3</td></tr>
    <tr><td id="2">1.4</td></tr>
    <tr><td id="100">1.5</td></tr>
    <tr><td id="23">1.6</td></tr>
</table>

例如,我想从我知道其 id 的行中淡出第 2 <tr>,在这种情况下,淡出动画必须在<tr><td id="260">1.3</td></tr>

更清楚的是,这是最终的期望结果:

$("#"+"260").closest("tr").fadeOut();

谢谢

如果您需要在已知行之后获取第 n 行,您可以使用 index:eq 选择器执行以下操作:

var n = 2;
var index = $("#20").closest("tr").index() + n;
$('.mytable1 tr:eq(' + index + ')').fadeOut();

演示:http://jsfiddle.net/896kxjn1/14/

如果你知道表中元素的索引 :nth-child(index) 可以是一个解决方案,

$("table tr:nth-child(2)").fadeOut();

如果你只知道id,而不是索引,那么获取该元素的索引,

// added 1 as .index() is indexed with 0 but in :nth-child(n) n is indexed 1
var elementIndex = $("#20").parent().index() + 1;
$("table tr:nth-child(" + elementIndex + ")").fadeOut();

js小提琴

资源:nth-child(index), .index()

我想淡出行中的第 2 个

然后你可以用:eq(index)来做到这一点:

 $('.mytable1 tr:eq(1)').fadeOut();

由于:eq()是基于zero, 0的,因此它的索引从 0 开始,因此第二项位于索引 1 处。

您也可以使用 nextAll,然后按索引:

$("#"+"20"+"").closest("tr").nextAll('tr').eq(n-1).fadeOut();

这样,如果您不想,就不必从桌子本身开始。

小提琴

显然,有一百万个更好的方法来使用jQuery的功能来做到这一点,我甚至不知道存在。

但是,我将发布我的答案,以便展示一种公平、程序化的方式来实现这一目标。它可能有助于某人理解解决此问题背后的思维过程。

// Create an array of tr elements from your table
row_list = $('table.mytable1 tr');
// Get the actual DOM element selected by jQuery with [0]
selected_row = $("#"+"20").closest("tr")[0];
// Use some function to set "nth"
nth_add = 2;
for (var i = 0; i < row_list.length; i++) {
    // Find the index of the current element, and add nth
    if (row_list[i] == selected_row) {
        select_new_index = i + nth_add;
        break;
    }
}
// Perform your manipulation on the index + nth element.
$(row_list[select_new_index]).fadeOut();

这是更新的JSFiddle。