javascript 选择倒数第二个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22605785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:27:35  来源:igfitidea点击:

Select second to last element

javascriptjqueryjquery-selectors

提问by Belsen

i need to select the value of second to last input selectable element:

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

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

The select input tag are inside tr tags.

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

If I use $("select.x").last(), jQuery select the last element. I need to select second to last.

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

回答by Anton

You can use .prev()

您可以使用 .prev()

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

回答by Gras Double

You can use .eq()with negative indexes:

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

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


These negative indexes are "1-indexed": -1gives the last element, -2the penultimate, and so on.


这些负索引是“1-indexed”:-1给出最后一个元素、-2倒数第二个元素,依此类推。

回答by Christoph

All of the below will do the trick (select the second last element):

以下所有内容都可以解决问题(选择倒数第二个元素):

$("select.x").eq(select.length - 1)

$("select.x:nth-last-of-type(2)")

$("select.x:nth-last-child(2)")

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

回答by Anubhav Chaudhary

You need to use "nth-last-child(2)" of jquery, this selects the second last element.

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

You can check this here:

你可以在这里检查:

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

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

回答by Irvin Dominin

You can use :lastselector and move to the preceding element using prev:

您可以使用:last选择器并使用以下方法移动到前面的元素prev

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

Ref:

参考:

Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

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

Sample demo: http://jsfiddle.net/IrvinDominin/ck8XP/

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

回答by Belsen

The solutions with .prev() or nth-last-child() don't works.

.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>

The problem is the last().prev() functions return the the object <a>which i suppouse come first the select one.

问题是 last().prev() 函数返回<a>我认为第一个选择的对象。

The nth-last-of-type(2) selector instead return an empty object.

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