JQuery: Hide children, show nth child?

柔情痞子 提交于 2019-12-30 12:23:13

问题


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.



来源:https://stackoverflow.com/questions/17035337/jquery-hide-children-show-nth-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!