Help with debugging JQuery Fade Script
For one of my first ventures into JQuery, I have the very simple goal of stepping through the children of a div and fading them in and out one by one. For some reason though, if I manually define an index for nth-child
, say 1, then the first child fades in and o开发者_JAVA技巧ut four times. If I use the variable "i", however, then all of the children fade in and out four times. Why is this happening?
Here is my code:
<div id="slideshow">
<p>Text1</p>
<p>Text2</p>
<p>Test3</p>
<p>Text4</p>
</div>
<script>
$(document).ready(function() {
var $elements = $('#slideshow').children();
var len = $elements.length;
var i = 1;
for (i=1;i<=len;i++)
{
$("#slideshow p:nth-child(i)").fadeIn("slow").delay(800).fadeOut("slow");
}
});
</script>
Each of the paragraphs is set to display: none;
initially.
You need to escape i
. Right now, nth-child
is looking for the child that has an index of i
, not of 0
, 1
, 2
, etc. So instead, use:
$('#slideshow p:nth-child(' + i + ')').fadeIn('slow').delay(800).fadeOut('slow');
However, I don't think that will do one at a time; in fact, I'm pretty sure it won't. If it doesn't, try something like this:
var delay = 0;
$('#slideshow p').each(
function (index, item)
{
$(this).delay(delay).fadeIn('slow').delay(800).fadeOut('slow');
delay += 2200;
}
);
That's untested, but should be decent pseudocode at the very least.
When you manually enter a index (1), then you loop 4 times and fadein the first child 4 times. When you use i they will all fadeIn four times since i inside a string is not a reference to the i variable, it's just part of the string.
$(document).ready(function() {
var $elements = $('#slideshow').children();
var len = $elements.length;
var i = 1;
for (i=1;i<=len;i++)
{
$("#slideshow p:nth-child("+i+")").fadeIn("slow").delay(800).fadeOut("slow");
}
});
Should work, notice "+i+"
A better way to do this is:
$(function(){
$('#slideshow p').each(function(i, node){
setTimeout(function(){
$(node).fadeIn("slow").delay(800).fadeOut("slow");
node = null; //prevent memory leak
}, i * 800);
});
});
I am not saying this impossible but in the end it will be pointless to use even if you get it to work, as it will fail on IE.
refer here. http://css-tricks.com/how-nth-child-works/
精彩评论