使用 jQuery 从选择中获取下一个或上一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/981981/
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
Using jQuery to get the next or previous element from a selection
提问by chrismar035
How can I get the previous or next element from a jQuery selection?
如何从 jQuery 选择中获取上一个或下一个元素?
Basically, I will have a set of elements, say all inputs:
基本上,我将有一组元素,比如所有输入:
$('input')
When I have a single input, I also need to get the previous and next input. Something like:
当我只有一个输入时,我还需要获取上一个和下一个输入。就像是:
$(this).prev('input')
$(this).next('input')
However, the inputs are not siblings and I don't want just the next DOM element. I want the next element in the jQuery selection (inputs in this case).
但是,输入不是兄弟元素,我不想要下一个 DOM 元素。我想要 jQuery 选择中的下一个元素(在这种情况下是输入)。
I know I can iterate through a jQuery selection with
我知道我可以遍历 jQuery 选择
.each(function(...
But I don't need to go over all of the elements, just the one before and after.
但我不需要遍历所有元素,只需要遍历之前和之后的元素。
The elements will also be dynamically ordered (using jQuery UI sortables).
元素也将被动态排序(使用 jQuery UI 排序)。
回答by Pim Jager
You could do something like this:
你可以这样做:
var inp = $('input');
var index = inp.index(this);
var next = inp[index+1];
var prev = inp[index-1];
Note that prev
and next
, just like this are not jQuery objects but DOM object now. To make them jQuery objects you need to wrap them in the $()
function.
请注意,prev
and next
,就像现在这样不是 jQuery 对象而是 DOM 对象。要使它们成为 jQuery 对象,您需要将它们包装在$()
函数中。