簡體   English   中英

用jQuery選擇下一個div?

[英]Select next div with jquery?

 //$(document).ready(function(){ $('.next').click(function(){ $('.box').fadeOut(); $('.box').next().fadeIn(); }); //}); 
 .box{ border:solid 1px #ccc; padding: 20px; width:10%; display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="next" style="cursor:pointer;">next</a> <br><br> <div class="box" style="display:block;"> 1 </div> <div class="box"> 2 </div> <div class="box"> 3 </div> <div class="box"> 4 </div> 

我有一個div .box和下一步按鈕。 如果我單擊“ next按鈕,但不是全部,則只需要選擇下一個div。 例如,如果我在顯示box 1同時單擊“ next按鈕,則應顯示的下一個框是2 ,依此類推。 但是現在它顯示2 3 4 這個怎么做 ?

您可以使用$(.box:visible)獲取第一個可見的div,然后在其下一個div上淡入。 您還可以添加對最后一個元素的檢查,在這種情況下,您可以淡入第一個元素。 像這樣的東西:

 //$(document).ready(function(){ $('.next').click(function(){ var visibleBox = $('.box:visible'); $(visibleBox).fadeOut(); if(!$(visibleBox).next('div').length) $('.box').first().fadeIn(); else $(visibleBox).next().fadeIn(); }); //}); 
 .box{ border:solid 1px #ccc; padding: 20px; width:10%; display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="next" style="cursor:pointer;">next</a> <br><br> <div class="box" style="display:block;"> 1 </div> <div class="box"> 2 </div> <div class="box"> 3 </div> <div class="box"> 4 </div> 

之所以顯示2 3 4是因為您正在選擇所有 .box元素,即1 2 3 4

.next()1 = 2

.next()2 = 3

.next() of 3 = 4

.next() of 4 =無

您應該找到當前顯示的框,然后找到它的下一個同級。

// Filter by CSS rule
var $showing = $('.box').filter(function() {
    return $(this).css('display') === 'block';
}).fadeOut();

// or using :visible
$showing = $('.box:visible').fadeOut();

$showing.next().fadeIn();

您可以使用另一個類標記顯示的div。 例如,添加一個類display 然后將那個課程放在第一個方框中。 單擊下一步時,可以從當前顯示中刪除該類顯示,然后將其移到下一個顯示中。

的HTML

<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box display">
    1
</div>

<div class="box">
    2
</div>

<div class="box">
    3
</div>

<div class="box">
    4
</div>

的CSS

.box{
    border:solid 1px #ccc;
    padding: 20px;
    width:10%;
    display:none;
}
.display{
  display:block
}

jQuery查詢

$('.next').click(function(){
    var current = $('.box.display');

current.fadeOut().removeClass('display').next().fadeIn().addClass('display');
});

演示: https : //jsfiddle.net/dfaLnsmo/

如果我了解您的要求,則可以使用

$(document).ready(function(){
  var i = 1;
    $('.next').click(function(){
        $('.box').fadeOut();
        $('.box:nth-child(i)').fadeIn();
        if(i >= $('.box').length)
        i++;
        else
        i=1; 
    });
});

試試下面的jQuery

var curr = 1;
$('.next').click(function(){
  if(curr < $( ".box" ).length) {
    $('.box').hide();
    $( ".box" )[curr].style.display= "block";
    curr += 1; 
  }
});

這是工作的jsfiddel: https ://jsfiddle.net/Lv7yr820/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM