我正在使用上一个和下一个按钮进行遍历。如果我一直点击,它似乎会坏掉。我只想点击后退或下一步按钮,它不会中断。
var $currDiv = $("#start");
$("div").hide();
$currDiv.css("background", "red");
$("#1").click(function() {
$currDiv = $currDiv.next();
$("div").hide();
$currDiv.show();
});
var $currDiv2 = $("#startPrev");
$("div").hide();
$currDiv2.css("background", "red");
$("#2").click(function() {
$currDiv2 = $currDiv2.prev();
$("div").hide();
$currDiv2.show();
});
div {
width: 50px;
height: 50px;
margin: 10px;
float: left;
border: 1px black solid;
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p><button id ="1">Next</button></p> <p><button id="2">Back</button></p>
<div id="start">div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div id="startPrev">div6</div>
最佳答案
我在这里可能有点过火了。我没有将当前 div 保存在一个变量中,而是将当前元素的 index 保存在一个变量中,这样使用起来更容易一些。我将所有 div 放在一个父元素 (#parent) 中,这样我们就可以使用选择器“#parent>div”轻松地只选择我们关心的 div。
var currIndex = 0; // start at the first element
showCurrentDiv();
// hide all divs, then show only the current one
function showCurrentDiv() {
// hide all divs inside #parent
$("#parent>div").hide();
// of all divs inside #parent, show the nth div, where n=currIndex
$("#parent>div:eq("+currIndex+")").show();
}
$("#1").click(function() {
// if current div is not the very last div...
if (currIndex < $("#parent>div").length - 1) {
currIndex++; // ...then traverse to the next div
}
showCurrentDiv(); // update which divs are shown/hidden
});
$("#2").click(function() {
// if current div is not the very first div...
if (currIndex > 0) {
currIndex--; // ...then traverse to the previous div
}
showCurrentDiv(); // update which divs are shown/hidden
});
#parent>div {
width: 50px;
height: 50px;
margin: 10px;
float: left;
border: 1px black solid;
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p><button id ="1">Next</button></p> <p><button id="2">Back</button></p>
<div id="parent">
<div>div1</div>
<div>div2</div>
<div>div3</div>
<div>div4</div>
<div>div5</div>
<div>div6</div>
</div>
通常答案不应该只是重写代码,但我希望我至少已经彻底解释了我所做的一切。我使用 :eq() 选择器来指定我想要显示的 div,记录在案 here ;基本上它会选择与选择器匹配的第 n 个元素。
关于jquery遍历框消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31840214/