如何在jQuery中选择每对2个连续元素? [英] How do I select every pair of 2 sequential elements in jQuery?

查看:85
本文介绍了如何在jQuery中选择每对2个连续元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮我解决如何实现以下目标吗?我有一组未知大小的div。每个div都有一类.feature。我需要运行一个jQuery脚本来查找带有.feature的所有div,然后将所有子节点作为一系列对来查找。然后将每对提交给另一个jQuery函数。

Can anyone please help me to work out how to achieve the following? I have a set of divs of unknown size. Each div has a class of .feature. I need to run a jQuery script to find all divs with .feature and then find all children as a series of pairs. Each pair will then be submitted to a further jQuery function.

例如:

1. <div.feature/>
2. <div.feature/>
3. <div.feature/>
4. <div.feature/>
5. <div.feature/>

结果应该是1 + 2和3 + 4配对在一起,这样我就可以打电话了每个单独的集合上的另一个jQuery函数。

The result should be that 1+2 and 3+4 get paired together such that I can then call another jQuery function on each of these individual sets.

我知道我可以简单地将每个对包装在一个外部div中,然后找到每个包装器divs children但是我想如果可能的话,避免更改标记。

I know that I can simply wrap each pair in an outer div and then find each wrapper divs children but I'd like to avoid changing the markup if possible.

推荐答案

var pairs = [];
$('div.feature').each(function(i, div) {
  var i_over_2 = Math.floor(i / 2);
  if (!pairs[i_over_2]) pairs[i_over_2] = $();
  pairs[i_over_2] = pairs[i_over_2].add(div);
});
$.each(pairs, function(i, p) {
  p.doSomethingToAPair();
});

想法是建立一个jQuery对象数组。

The idea is to build up an array of jQuery objects.

编辑看起来像1.4添加$()来获取一个空的jQuery对象。

edit looks like 1.4 added "$()" to get an empty jQuery object.

再次编辑 durr Javascript有花车: - )

edit again durr Javascript has floats :-)

嘿@Adam:如果我们有这个jQuery扩展(当然这是玩具版):

Hey @Adam: if we had this jQuery extension (this is a toy version of course):

jQuery.fn.zip = function(s) {
  var o = $(s);
  return this.map(function(i, e) {
    return $(e).add($(o[i]));
  });
};

然后我们可以像这样建立对数组:

then we could build the "pairs" array like this:

var pairs = $('div.feature:even').zip('div.feature:odd');

这篇关于如何在jQuery中选择每对2个连续元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆