我有一系列名为“page-1”“page-2”“page-3”...“page-99”的页面。有没有一种方法可以进行导航,以便每当我单击“下一页”按钮时它都会转到下一页,如果我单击“上一页”它会根据当前页码转到上一页。我想知道是否有针对此问题的 javascript 解决方案,因为我从未使用过 PHP。
<a href="#" id="next">next</a> <!--it will go to page-3-->
<a href="#" id="prev">previous</a> <!--it will go to page-1-->
最佳答案
这应该可以帮助您入门(从您的原始代码开始)。
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
var nav = $(this).attr('data-nav');
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num--;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]');
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-2" data-nav="next">next</a> <!--it will go to page-3-->
<a href="#" class="page-2" data-nav="prev">previous</a> <!--it will go to page-1-->
当然,这样会更简单:
$('a[class^=page]').click(function(e){
e.preventDefault();
var num = this.className.split('-')[1]; //2
//window.location.href = "page-"+num+'.html'; //The "real" code
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="page-1" >next</a> <!--it will go to page-3-->
<a href="#" class="page-3" >previous</a> <!--it will go to page-1-->
这将是最简单的(使用文件名):
//className *starts with* nav-
$('[class^=nav-]').click(function(e){
e.preventDefault();
var fileName = location.pathname.split("/").slice(-1);
var fileName = 'http://page-2.html'; //FOR DEMO ONLY
//alert(fileName); //should respond page2.html
var num = fileName.split('-')[1]; //2
var nav = this.className.split('-')[1]; //next
if (nav == 'next'){
num = parseInt(num)+1;
//window.location.href = "page-"+num+'.html';
}else{
num = parseInt(num)-1;
//window.location.href = "page-"+num+'.html';
}
alert('Navigating to: [ page-' +num+ '.html ]'); //For demo purposes only
});
a{padding:10px;border:1px solid #ccc;border-radius:5px;text-decoration:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="nav-next" >next</a> <!--it will go to page-3-->
<a href="#" class="nav-prev" >previous</a> <!--it will go to page-1-->
关于javascript - 创建上一个/下一个 html 页面导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111145/