开发者

JS/jQ - Move horizontally across containers

开发者 https://www.devze.com 2023-03-24 10:57 出处:网络
I have a series of DIV elements with more DIV elements inside of them, of variable lengths.As example code to simplify the matter...

I have a series of DIV elements with more DIV elements inside of them, of variable lengths. As example code to simplify the matter...

<div class="container">
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
</div>
<div class="container">
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
</div>
<div class="container">
 <div class="inset"></div>
 <div class="inset"></div>
 <div class="inset"></div>
</div>

I have been using jQuery's each() to move between the "inset" DIVs. However, I've come to the realization I'm going to have to move between the first inset DIV in the first container, to the first in the second container, to the first in the third, then to the second in the first container开发者_C百科, and so forth.

The problem is, I have no idea how to do this.

If it helps, the main purpose for moving these is to change their background colors in a preset pattern. I do not believe it's possible to redo the structure of the code.

Is there any way this can be done?


It can, though my approach is not the most elegant.

Here's a sample (need to have Firebug installed to see the output): http://jsfiddle.net/ceZkr/

var maxlength = 0; // first need to find container with the most insets.
$('.container').each(function(index, val){
    var curlength = $(this).find('.inset').length;
    if(curlength > maxlength) {
        maxlength = curlength;
    }
});

console.log('our maxlength: ' + maxlength);

for(var i = 0;i<maxlength; i++) {
    $('.container').each(function(){
        var $box = $(this).find('.inset:eq('+i+')');
        if($box.length) {
            console.log( $box.text() );
        }

    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号