简体   繁体   English

jQuery next方法替代

[英]jQuery next method alternative

jquery's next method is looking for next sibling. jQuery的下一个方法正在寻找下一个同级。 But i need next element which is not sibling. 但是我需要下一个没有兄弟的元素。 I just need to iterate next elements in selector. 我只需要迭代选择器中的下一个元素。 For example: 例如:

$('.wrapper .parent div').next(); // in here next method looks first element
// in selector and get next sibling of it.

What i want is next matched element in selector. 我想要的是选择器中的下一个匹配元素。 Simply calling each method will provide it to me but i dont need to iterate whole collection. 只需调用每种方法即可将其提供给我,但我不需要迭代整个集合。

slice method will help me iterate manualy by controlled me but providing slice parameters makes it harder to use. slice方法将通过控制我来帮助我手动进行迭代,但是提供slice参数会使它更难使用。

What can be another solution. 什么是另一种解决方案。

If you have a jQuery selector with multiple objects in it, there are a number of ways you can iterate or get individual elements in that list. 如果您有一个带有多个对象的jQuery选择器,则可以使用多种方法来迭代或获取该列表中的单个元素。

This tells you how many are in the collection: 这告诉您集合中有多少个:

$('.wrapper .parent div').length

This gets you the HTML DOM element for any item in the collection (depending upon what number you pass as the parameter to get() : 这将为您获取集合中任何项目的HTML DOM元素(取决于您将什么数字作为参数传递给get()

$('.wrapper .parent div').get(0);

This gets you a jQuery object for any item in the collection (depending upon what number you pass as the parameter to eq() : 这将为您获取集合中任何项目的jQuery对象(取决于您将什么作为参数传递给eq()

$('.wrapper .parent div').eq(0);

You can iterate through the whole collection several ways. 您可以几种方式遍历整个集合。 You can use .each() : 您可以使用.each()

$('.wrapper .parent div').each(function(index) {
    // "this" will be set to the DOM element you are iterating in the collection
});

Or, you can iterate manually several different ways: 或者,您可以手动迭代几种不同的方式:

var items = $('.wrapper .parent div');
for (var i = 0; i < items.length; i++) {
    // items.get(i) is the DOM element
}

Or, you can even just convert the object into an array of DOM elements: 或者,您甚至可以将对象转换为DOM元素数组:

var domArray = $('.wrapper .parent div').makeArray();
for (var i = 0; i < domArray.length; i++) {
    // domArray[i] is the DOM element
}

Use jQuery eq method and pass the index to it. 使用jQuery eq方法并将索引传递给它。 It Reduces the set of matched elements to the one at the specified index. 它将匹配元素的集合减少到指定索引处的元素。

$('.wrapper .parent div').eq(1);//Whatever index you need pass into it. It is 0 based.

http://api.jquery.com/eq/ http://api.jquery.com/eq/

Perhaps try $(".wrapper .parent div:nth-child(2)") instead? 也许尝试$(".wrapper .parent div:nth-child(2)")代替?

Or $(".wrapper .parent div:nth-child(" + i++ + ")") for the next-in-set functionality, where i is the first one you want to get. $(".wrapper .parent div:nth-child(" + i++ + ")")获得下一个内置功能,其中i是您要获取的第一个功能。

JQuery nth-child selector documentation . jQuery nth-child选择器文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM