基本上我的 DIV 看起来像这样。
<div id="group">
<div id="one">one</div>
<div style="display:none" id="two">two</div>
<div style="display:none" id="three">three</div>
<div style="display:none" id="four">four</div>
</div>
<div id="next">next</div>
<div style="display:none" id="prev">prev</div>
<div style="display:none" id="prev">SUBMIT</div>
这只是一个例子,我什至可以有 10 或 20 个 div。
在此示例中,我想从一导航到四。当它到达末尾时,它必须隐藏 next
按钮并显示 submit
按钮。当我导航回到第一页时,它必须隐藏 prev
按钮
到目前为止,这是我尝试过的:
$("#next").click(function () {
$("#prev").show();
$("#one").hide();
$("#one").addClass("current");
$(".current").next().addClass("current").show();
$(".current").prev().removeClass("current").hide();
});
$("#prev").click(function () {
$("#prev").show();
$("#one").hide();
$("#one").addClass("current");
$(".current").prev().addClass("current").show();
$(".current").next().removeClass("current").hide();
});
这适用于某些导航,但它会变得困惑。一些指导将对我和其他人有所帮助。
谢谢
JSFIDDLE:http://jsfiddle.net/aVJBY/450/
最佳答案
我看到你有一个答案,但我会建议一个更结构化的方法来重用单个代码路径:
http://jsfiddle.net/TrueBlueAussie/aVJBY/460/
function updateItems(delta)
{
var $items = $('#group').children();
var $current = $items.filter('.current');
var index = $current.index();
var newIndex = index+delta;
// Range check the new index
newIndex = (newIndex < 0) ? 0 : ((newIndex > $items.length) ? $items.length : newIndex);
if (newIndex != index){
$current.removeClass('current');
$current = $items.eq(newIndex).addClass('current');
// Hide/show the next/prev
$("#prev").toggle(!$current.is($items.first()));
$("#next").toggle(!$current.is($items.last()));
}
}
$("#next").click(function () {
updateItems(1);
});
$("#prev").click(function () {
updateItems(-1);
});
注意事项:
- 范围上限可以简化,但您明白了。
- 您不需要初始化内联样式,因为这可以在 CSS 中完成。
- 这不受内容的任何限制。这里我又添加了 6 个 div:http://jsfiddle.net/TrueBlueAussie/aVJBY/463/
更新
因为我不喜欢页面中初始“状态”需要样式的情况,这里有一个新版本也可以正确设置初始状态而没有任何初始样式(使用 0 delta ).我还删除了一个多余的变量:
function updateItems(delta)
{
var $items = $('#group').children();
var $current = $items.filter('.current');
$current = $current.length ? $current : $items.first();
var index = $current.index() + delta;
// Range check the new index
index = (index < 0) ? 0 : ((index > $items.length) ? $items.length : index);
$current.removeClass('current');
$current = $items.eq(index).addClass('current');
// Hide/show the next/prev
$("#prev").toggle(!$current.is($items.first()));
$("#next").toggle(!$current.is($items.last()));
}
$("#next").click(function () {
updateItems(1);
});
$("#prev").click(function () {
updateItems(-1);
});
// Cause initial selection
updateItems(0);
关于javascript - 使用 next/prev 浏览多个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294145/