JQuery: Hide children, show nth child?

2019-02-20 05:07发布

问题:

This is really weird and should be simple.

I have an array of images within a tags within a div, eg:

<div id="images">
<a href="#"><img src="img1.jpg"/></a>
<a href="#"><img src="img2.jpg"/></a>
<a href="#"><img src="img3.jpg"/></a>
</div>

I want to hide all of them, but loop through and show the nth one, so I created this image slider style script:

var atags = $('#images').children().length;

$('#images').children().hide();

$('#images a:first').show();

var i=0

while (i <= atags){

$('#images').children().delay(4000).hide();

$("images:nth-child(" + i + ")").show();

i = i + 1;
}

The issue is that no other a tags, despite the first out side the loop, get displayed. They all remain hidden dispite the .show(). It appears the line $("images:nth-child(" + i + ")").show(); just doesnt work.

Can anyone point me in the right direction with this?

回答1:

images != #images plus you need to select the actual images not the container:

$("#images img:nth-child(" + i + ")").show();

But I would just use eq, not sure if the above will work given that the images are inside a tag:

$("#images img").eq(i).show();

In any case, you don't need that while loop, just use jQuery's each to loop the collection.

Also note that delay only works if there's an animation queue and this not your case.