1

我需要创建一个数组数组。我有一个相当广泛的 if/else 循环工作,但我认为我可以使用 jQueries nextUntil 函数对其进行重构。根据我所看到的,我走在正确的轨道上,但我的结果在两个方向上都没有达到我的需要。

这是HTML

var array = [[]];

<ul id="list">
    <li class="get-it">1</li>
    <li class="get-it">2</li>
    <li class="ignore-it">3</li>
    <li class="get-it">4</li>
    <li class="get-it">5</li>
    <li class="ignore-it">6</li>
    <li class="get-it">7</li>
    <li class="get-it">8</li>
    <li class="ignore-it">9</li>
    <li class="get-it">10</li>
    <li class="get-it">11</li>
</ul>

这是我尝试抓取 .get-it 列表项的几种方法

// returns single-item array of all .get-it items
array.push( $( '#list' ).children().nextUntil( '.ignore-it' );

// returns 8 single-item array of .get-it items
$row.children().nextUntil( '.ignore-it' ).each(function(){
    array.push( $(this) );
});

这是我真正需要返回的

// what I need returned
array = [
    [ li[0], li[1] ],
    [ li[3], li[4] ],
    [ li[6], li[7] ],
    [ li[9], li[10] ]
]
4

2 回答 2

3

这将起作用:

var array = $('.get-it:first, .ignore-it + .get-it').map(function() {
    return $(this).add($(this).nextUntil('.ignore-it'));
}).get();

JSFiddle

基本上它是这样工作的:

// grab the first .get-it, as well as all .get-it
// elements that follow an .ignore-it element
$('.get-it:first, .ignore-it + .get-it')

// map each of those items into an array that contains
// itself, plus all .get-it elements up until the next
// .ignore-it element
.map(function() {
    return $(this).add($(this).nextUntil('.ignore-it'));
})

// convert our jQuery collection into a regular array
.get();
于 2014-10-15T14:45:37.573 回答
1

你可以这样做

var array = [], tempArr = $('#list > li.get-it').map(function(){ return $(this); });
while(tempArr.length > 0)
   array.push(tempArr.splice(0, 2));  // splice it into two

演示

上面所做的是获取元素并将它们分成两部分。

于 2014-10-15T14:36:05.727 回答