[英]How do I loop through divs with left and right buttons?
我試圖用左右按鈕循環顯示6個div,其想法是您可以左右移動,所選的div將具有“ active”類,然后當您單擊左側或右側時,它將移動到下一個div並從上一個div中刪除該類,然后將其添加到該行的下一個div中。
這是我的Js
$(function () { // this is a shortcut for document ready
var stuff = ['box1', 'box2', 'box3', 'box4', 'box5','box6'],
counter = 0;
console.log(stuff[counter]); // your initial value
$('.right').click(function () {
counter = (counter + 1) % stuff.length;
valueNw = stuff[counter];
console.log(valueNw);
});
$('.left').click(function () {
counter = (counter - 1) % 1;
console.log(stuff[counter]);
});
});
任何想法都將不勝感激,我有前進的方向,但沒有前進的方向,如果有更好的方法可以做到這一點,請告訴我。
在您的代碼(counter - 1) % 1
始終為0
因此始終指向0
。 相反,在counter
為0
情況下,通過將值替換為stuff.length
來更改向后條件以避免負值。
$(function() { // this is a shortcut for document ready var stuff = ['box1', 'box2', 'box3', 'box4', 'box5', 'box6'], counter = 0; console.log(stuff[counter]); // your initial value $('.right').click(function() { counter = (counter + 1) % stuff.length; valueNw = stuff[counter]; console.log(valueNw); }); $('.left').click(function() { // replace with stuff.length if counter holds 0 and decrement counter = (counter || stuff.length) - 1; console.log(stuff[counter]); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="right">right</button> <button class="left">left</button>
該答案是對您在@Pranav答案中的問題的答復。 這就是我根據右/左按鈕單擊選擇div的方式。
var eleName = ".box1";
var eleCount = 0;
var currIndex = 1;
$(function () { // this is a shortcut for document ready
eleCount = $('.box').length;
$(eleName).toggleClass('active');
ShowConsoleInfo();
$('.right').click(function () {
if(currIndex <= eleCount - 1){
//Toggle current box.
$(eleName).toggleClass('active');
//Build the name by incrementing current index.
currIndex++;
eleName = '.box' + currIndex;
//Toggle newly selected box.
$(eleName).toggleClass('active');
ShowConsoleInfo();
}
});
$('.left').click(function () {
if(currIndex >= 2){
//Toggle current box.
$(eleName).toggleClass('active');
//Build the name by decrementing current index.
currIndex--;
eleName = '.box' + currIndex;
//Toggle newly selected box.
$(eleName).toggleClass('active');
ShowConsoleInfo();
}
});
});
function ShowConsoleInfo(){
console.clear();
console.log("Current Index: " + currIndex);
console.log("Element Count: " + eleCount);
console.log("Current Box name: " + eleName);
};
請參閱CodePen上Addam Boord( @BOORDA )的Pen Right Left Div選擇示例[jQuery] 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.