简体   繁体   中英

Selecting next div jquery

I am trying to select the .next() div to work within a carousel.

However, it seems to be returning all .children() rather than the .next()

HTML

<nav class="slider-navigation">
  <div class="left-arrow"></div>
  <div class="right-arrow"></div>
</nav>

<div class="slides">
  <div class="slide" id="slide1"></div>
  <div class="slide" id="slide2"></div>
  <div class="slide" id="slide3"></div>
  <div class="slide" id="slide4"></div>
</div>

JQUERY

$(".left-arrow").click(function () {

  var currentSlide = $(this).parent().siblings(".slides").children().next();

  // Do something with currentSlide.

});

When I console.log(currentSlide) in the browser it returns all 4 children of .slides .

The same happens for $(".right-arrow").click() I just did not want to add duplicate code

Any help?

Thanks

another option is to set the first element to the "current" class and use it to start the navigation between the slides.

*on prev control click, if there is no element before this one so nothing will happen and vice versa, so that's ok but if you want it to change direction after the last/first element got the "current" class so tell me and i will update the code...

Here it is:

HTML:

<nav class="slider-navigation">
  <div class="left-arrow">left</div>
  <div class="right-arrow">right</div>
</nav>

<div class="slides">
  <div class="slide current" id="slide1"></div>
  <div class="slide" id="slide2"></div>
  <div class="slide" id="slide3"></div>
  <div class="slide" id="slide4"></div>
</div>

Jquery:

$(document).ready(function(){
    $(".left-arrow").click(function(){
        $('.current').prev().addClass('current');
        $('.current:first').next().removeClass('current');
    });
    $(".right-arrow").click(function(){
        $('.current').next().addClass('current');
        $('.current:last').prev().removeClass('current');
    });
});

live example: http://jsfiddle.net/spvLpjct (i've put some CSS to help you understand it).

If the current slide is visible and the rest are hidden you could use:

$(".left-arrow").click(function () {

  var currentSlide = $(".slides > .slide:visible").next();

  // Do something with currentSlide.

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM