开发者

Show/Hide divs with same class - jquery

开发者 https://www.devze.com 2023-01-02 09:35 出处:网络
I have 1 div that will contain 3-5 divs with the same class. Below the div is an anchor. I would like for when this anchor is clicked it will hide the first div and then show the second. Another click

I have 1 div that will contain 3-5 divs with the same class. Below the div is an anchor. I would like for when this anchor is clicked it will hide the first div and then show the second. Another click would show the next and so on. I have set display:none on all divs but the first so only one is currently showing. I just can't figure out how to hide the first and then show the second, then third, then next when clicking the anchor.

<div class="container-div">
<div class="inner-div">...</div>
<div class="inner-div" style="display:none;">...</div>
<div class="inner-div" style="display:none;">...</div>
<a href="#" class="more">More</a>
</div>

So when the more anchor is clicked it would show one inner-div one at a time. Any suggestions or ideas would be greatly appreciated. Also, I would like to use jqu开发者_如何学JAVAery to accomplish this.


You could do something like:

$(".inner-div:visible").hide().next().show();

This would find the first visible div with that class, then navigate to the next child and show it.

This assumes that:

  1. The divs are siblings
  2. If the last div is showing, clicking the button will just hide it and show nothing.

To cycle back to the beginning is slightly trickier. I might do something like:

var next = $(".inner-div:visible").hide().next();
if (next.length > 0)
    next.show();
else
    $(".inner-div:first").show();

To instead simply stop cycling after the last div is showing, you could do:

var current = $(".inner-div:visible");
if (current.next().length > 0)
    current.hide().next().show();


how about giving the invisible divs an additional class, say invisible, and then specify the display:none in the css for that class.

Whenever the link is pressed add the class to any div in the container that hasn't already got it, and then remove the class from the next div with the inner-divclass (or the first inner-div if you are at the buttom)


don't know if you are restricted by your requirements, but I think cycle or carousel plugins will also work fine for this kind of work.

0

精彩评论

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