用Javascript分页错了

时间:2015-08-28 02:40:40

标签: javascript pagination

我用JS编写分页

像这样

<a id="prev">Previous Page</a>
<a id="next">Next Pages</a>

和JS代码一样

$('#next').click(function(){ 
   var url = window.location.href; 
   var urllen = url.length;
   var cur = parseInt((url.substr(urllen-1)).substr(0,1)); 
   var nurl = url.substr(0,(urllen-1))+(cur+1); 
   if(cur=="NaN") { window.location = (url); } 
   else { window.location = (nurl); } 
}); 
$('#prev').click(function(){ 
   var url = window.location.href; 
   var urllen = url.length; 
   var cur = (url.substr(urllen-1)).substr(0,1); 
   if(cur==1||cur=="NaN") { window.location = (url); } 
   else { var nurl = url.substr(0,(urllen-1))+(cur-1); window.location = (nurl); } 
});

和我的网址一样

http://localtest/rftpages/record.html?s=1&l=1&bike_id=1

让我解释一下我使用JavaScript方法的原因是我不想更改包含我在整个页面中使用的页面变量的URL

所以我正在做的是获取所有的URL并将bike_id值更改为next / prev

问题是当它数到19或像

这样的网址时
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19

然后我再次进入URL将变为

http://localtest/rftpages/record.html?s=1&l=1&bike_id=110

任何想法/建议来解决这个问题?

由于

1 个答案:

答案 0 :(得分:2)

你应该做的是从查询字符串中抓取页面,然后根据点击的内容递增或递减页面。

你只需要这个函数来获取参数:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

所以,如果我假设你的例子:

http://localtest/rftpages/record.html?s=1&l=1&bike_id=19

然后您可以将您的功能更改为:

$('#next').on("click", function() {
    var currentPageParameter = getParameterByName("bike_id");
     var s = getParameterByName("s");
     var l = getParameterByName("l");
     var myPage = parseInt(currentPageParameter);
     if (! isNaN(myPage )) {
           myPage = myPage + 1;
           window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
      }
});
$('#prev').on("click", function() {
 var currentPageParameter = getParameterByName("bike_id");
     var s = getParameterByName("s");
     var l = getParameterByName("l");
     var myPage = parseInt(currentPageParameter);
     if (! isNaN(myPage )) {
           myPage = myPage - 1;
           window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
      }
});