我目前拥有它,以便在您点击“页面”号码时更改文本块,但我想添加上一个和下一个按钮。
在此处查看我当前的版本:http://jsfiddle.net/ZBWqS/
我开始前往的每个解决方案都会变成一堆乱七八糟的非工作代码。
对不起noob-JS问题。
<div id="1" style="display: block;">
<p>This is the first block of text</p>
<p class="page">
1 of 3
</p>
</div>
<div id="2" style="display: none;">
<p class="red">This is the second block of text</p>
<p class="page">
2 of 3
</p>
</div>
<div id="3" style="display: none;">
<span>This is the third block of text</span>
<p class="page">
3 of 3
</p>
</div>
<div class="bottom">
<a href="#" onclick="show('1'), hide('2'), hide('3'); return false;">1 </a><a href="" onclick="show('2'), hide('1'), hide('3'); return false;">2 </a><a href="" onclick="show('3'), hide('2'), hide('1'); return false;">3 </a>
</div>
<script>
function show(id) {
document.getElementById(id).style.display = 'block';
}
function hide(id) {
document.getElementById(id).style.display = 'none';
}
</script>
答案 0 :(得分:0)
保留一个变量来存储你的位置,递增/递减它,然后根据该变量显示内容。
// hold where we are right now. For previous and next to make sense,
// you have to know where you are.
var current = 1;
// function to go to previous
var prev = function() {
current -= 1;
if (current < 1) current = 1; // can't go too far previous
showContent();
};
// function to go next
var next = function() {
current += 1;
if (current > 3) current = 3; // can't go too far next
showContent();
};
// Update what content we are showing based on the "current" index
var showContent = function() {
var display;
for (var i = 1; i <= 3; i++) {
if (i == current) {
display = 'block';
} else {
display = 'none';
}
document.getElementById(i).style.display = display;
}
};
// bind the prev and next function to the links
document.getElementById('prev').onclick = prev;
document.getElementById('next').onclick = next;
// Setup the initial state of the content
showContent();
答案 1 :(得分:0)
我还构建了一个重构版本的代码,你可以决定你更喜欢哪一个;)
<强> HTML 强>
<div id="1" class="pagecontainer" style="display: block;">
<p>This is the first block of text</p>
<p class="page">
1 of 3
</p>
</div>
<div id="2" class="pagecontainer" style="display: none;">
<p class="red">This is the second block of text</p>
<p class="page">
2 of 3
</p>
</div>
<div id="3" class="pagecontainer" style="display: none;">
<span>This is the third block of text</span>
<p class="page">
3 of 3
</p>
</div>
<div class="bottom">
<a href="#" onclick="prev()">‹</a>
<a href="#" onclick="page('1')">1 </a>
<a href="#" onclick="page('2')">2 </a>
<a href="#" onclick="page('3')">3 </a>
<a href="#" onclick="next()">›</a>
</div>
<强> SCRIPT 强>
var currentPage = 1;
function page(pg)
{
var els = document.getElementsByClassName("pagecontainer");
for (var i = 0; i < els.length; i++)
{
var page_of_container = els[i].getAttribute("id");
els[i].style.display = page_of_container == pg ? 'block' : 'none';
}
currentPage = pg;
}
function prev()
{
if (currentPage <= 1) return;
page(currentPage -1);
}
function next()
{
if (currentPage >= document.getElementsByClassName("pagecontainer").length) return;
page(currentPage + 1);
}