Javascript Array not working correctly with $.makeArray
I'm trying to make an array out of a set of div's on a page using jQuery. I basically want to randomise the way they are displayed so for the moment, I'm just trying to cycle through them. Everything appears to work, except that I only ever see the last array item, even though it performs the action the same number of times as there are elements in the array, and adds the correct behaviour.
The JS is:
<script>
$(document).ready(function(){
var obj = $('.item');
var arr = $.makeArray(obj);
$('.array').html('');
$.each(arr, function(k,v){
$('.array').html(v).fadeIn(250).delay(2000).fadeOut(250);
});
});
</script>
And the markup is:
<div class="array">
<div class="item">First</div>
<div class="item">Second</div>
<div class="item">Third</div>
<div class="item">Fourth</div>
</div>
I'm not sure that it's relevant, but here's the CSS, just in case:
div.item {
display: inline; float: left; width: 960px; height: 260px; font-family: helvetica; font-size: 10px; text-align: center; background: #eee; border: solid 1px #888;
}
All I get is the div with the text "Fourth" fading in and out 4 times. This tells me it's iterating through the array fine (as it's using the count) but why am I only seeing the last 开发者_如何学编程element? Anyone any thoughts?
Thanks,
T
The loop is overwriting the content of the array div in every iteration of the loop. thus you only see the result of the last iteration.
When you use .html(...)
it is the same as .empty().append(...)
. So what you loop does is empty the content 4 times in a row, and only the append after the last empty will actually take effect.
If you wish the elements to fadein/fadeout one after another you can do it like this:
$(document).ready(function(){
var obj = $('.item');
$('.array').html('');
obj.each(function(i){
$('.array').append($(this).hide().delay(i * 2500).fadeIn(250).delay(2000).fadeOut(250));
});
});
you can see it running here: http://jsfiddle.net/9Xg8X/
Also worth mentioning is that the calls to the effect methods don't block. That is why the loop is already finished before the first effect occurs.
You don't say what you actually want, but if you want to have every element appended and appear/disappear one after another, you can do something like this:
$(document).ready(function(){
var obj = $('.item').detach();
var count = obj.length;
var target = $('.array');
var display = function(i) {
var element = $(obj[i]);
var cb = (i < count-1) ? function(){display(i+1)} : function(){};
element.appendTo(target).hide().fadeIn(250).delay(2000).fadeOut(250, cb);
};
display(0);
});
There is actually no need to use $.makeArray()
.
DEMO
精彩评论