选择倒数第二个元素

Select second to last element

本文关键字:元素 第二个 倒数第二 倒数 选择      更新时间:2023-09-26

我需要选择倒数第二个可选择输入元素的值:

<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>

选择输入标签在tr标签内。

如果我使用$("select.x").last(), jQuery选择最后一个元素。我需要选择倒数第二

您可以使用带有负索引的.eq():

$("select.x").eq(-2);


这些负索引是"1索引":-1给出最后一个元素,-2给出倒数第二个元素,以此类推。

可以使用。prev()

$("select.x").last().prev();

下面的所有元素都可以达到这个效果(选择倒数第二个元素):

$("select.x").eq(select.length - 1)
$("select.x:nth-last-of-type(2)")
$("select.x:nth-last-child(2)")
$("select.x").last().prev()

您可以使用:last选择器并使用prev:

移动到前面的元素
$("select.x:last").prev();

裁判:

获取集合中每个元素的前一个兄弟元素匹配的元素,可由选择器筛选。

示例演示:http://jsfiddle.net/IrvinDominin/ck8XP/

您需要使用jquery的"nth-last-child(2)",这将选择倒数第二个元素。

你可以在这里检查:

https://api.jquery.com/nth-last-child-selector/

.prev()或nth-last-child()的解决方案不起作用。

<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>

问题是last().prev()函数返回对象<a>,我认为它首先出现在select中。

第n -last-of-type(2)选择器返回空对象。