我一直在研究 StackOverflow 来寻找这个问题的答案。有与此相关的答案,但我没有找到针对此具体案例的答案。 我有一系列的 div。我想在页面首次加载时显示第一个,然后通过单击相应的“上一个”和“下一个”按钮按顺序移动到第二个、第三个等,或反向移动到第二个、第一个...。 任何时候只有一个 div 可见。 现在我正在朝着前进的方向努力。我认为使用一个针对点击时触发的不断变化的 div ID 的循环是可行的。我错了。
这是 HTML
<div class="container">
<div id="section1" class="first">
something in section 1
</div>
<div id="section2" class="ad">
<p>doing tricks with section 2</p>
</div>
<div id="section3" class="ad">
<p>and now is time for section 3</p>
</div>
<button id="hide">Hide</button>
</div>
<button id="show">Show</button>
这是 JS
$(document).ready(function () {
var count = $("div.container div").length;
//alert(count);
$('#hide').on('click', function () {
$('div.ad').hide(); // hide all divs but the first
});
for (var i=0; i< count; i++) {
$('#show').on('click', function () {
var j = i+1;
$('#section'+j).next().show();
$('#section'+(j+1)).prev().hide();
});
};
});
最佳答案
在您的问题中,count
始终为 3
,这就是您问题的开始。始终有三个 div
元素;问题是其中一些是隐藏的。它们从视线中消失,但并未从文档中消失。
$(function() {
$('#hide').click(function() {
$('.container > div:visible:last').hide();
});
$('#show').click(function() {
$('.container > div:not(:visible):first').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="section1" class="first">
something in section 1
</div>
<div id="section2" class="ad">
<p>doing tricks with section 2</p>
</div>
<div id="section3" class="ad">
<p>and now is time for section 3</p>
</div>
</div>
<button id="hide">Hide</button>
<button id="show">Show</button>
编辑:显然,我误解了这个问题。 (为什么你的按钮被称为“隐藏”和“显示”而不是“上一个”和“下一个”?!?)你想要的似乎是这样的:
$(function() {
$('.ad').hide();
$('#prev').click(function() {
var $prev, $current = $('.container > div:visible:first');
if ($prev = $current.prev()) {
$prev.show();
$current.hide();
}
});
$('#next').click(function() {
var $next, $current = $('.container > div:visible:first');
if ($next = $current.next()) {
$next.show();
$current.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="section1" class="first">
something in section 1
</div>
<div id="section2" class="ad">
<p>doing tricks with section 2</p>
</div>
<div id="section3" class="ad">
<p>and now is time for section 3</p>
</div>
</div>
<button id="prev">Prev</button>
<button id="next">Next</button>
关于javascript - 单击时一次仅顺序显示一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369668/