我只是想知道在该程序中,当我们按下按钮时,下一个兄弟姐妹将显示为红色,但是当最后一个元素出现时,程序将停止,我只是希望在最后一个元素之后,它再次出现在第一个
setup.js
require('jsdom-global')();
var nextDiv = $( "#start" );
nextDiv.css( "background-color", "red" );
$( "button" ).click(function() {
nextDiv = nextDiv.next();
$( "div" ).css( "background-color", "" );
nextDiv.css( "background-color", "red" );
});
答案 0 :(得分:1)
查看代码并与eq()
一起使用
var i=0;
var len=$('.box').length
$("button").click(function() {
if(i==len)
i=0;
nextDiv = $(".box:eq("+ i+ ")");
$(".box").css( "background-color", "" );
nextDiv.css( "background-color", "red" );
i++;
});
div{
border:1px solid black;
width:50px;
height: 50px;
display: inline-block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Move to Next</button>
<div class="box" id="start">div1 </div>
<div class="box">div2</div>
<div class="box">div3</div>
<div class="box">div4</div>
<div class="box">div5</div>
<div class="box">div6</div>
答案 1 :(得分:1)
这里我有另一种解决方法
var divs = $('.divs').find('div').length;
var count = 1;
$( "button" ).click(function() {
count++;
if( count > divs){
count = 1;
$('div').removeClass('active');
$('#start').addClass('active');
} else {
$('div.active').removeClass('active').next().addClass('active');
}
});
.divs div{
border:1px solid black;
width:50px;
height: 50px;
display: inline-block;
margin: 10px;
}
div.active{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divs">
<button>Move to Next</button>
<div id="start" class='active'>div1 </div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div>div6</div>
</div>
对于初学者来说很容易理解