jquery遍历框消失

标签 jquery html css

我正在使用上一个和下一个按钮进行遍历。如果我一直点击,它似乎会坏掉。我只想点击后退或下一步按钮,它不会中断。

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/

相关文章:

jquery - 单击 <a> 标签更改 <li> 的背景图像

javascript - 使您的 JavaScript 可维护

html - 具有背景渐变的背景图像

javascript - HTML 错误。标签未关闭

jquery - slideToggle siblings others 打开div

javascript - 想要在滚动 > 10 后平滑地显示导航栏

php - HTML/CSS/PHP 在特定页面上显示选定的元素

javascript - javascript eval() 可以获取变量名称并在使用前替换它们吗

javascript - jquery 在查找或过滤之前返回到元素

javascript - 为什么我的 JSFiddle 不工作? (放置脚本的位置)