我用 jquery 创建了一个分页系统,该脚本运行得很好,但是当我更改页面时,脚本使我由于刷新而返回到原始页面。
如何使刷新与分页配合使用?
谢谢
$(document).ready(function() {
setInterval(function(){
$("#results" ).load( "recherche.php");
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show();
var page = $(this).attr("data-page");
$("#results").load("recherche.php",{"page":page}, function(){
$(".loading-div").hide();
});
});
}, 1000);
});
<div id="results">
<div class="loading-div">
<img src="img/loader.gif">
</div>
</div>
最佳答案
感谢评论中提供的更多详细信息。我相信你的问题是“setInterval”...你可能只想在页面加载时运行此代码一次 - 然后ajax调用将接管。
在这种情况下,您需要使用setTimeout -setInterval每 1000 毫秒重复一次回调。 (在本例中)
$(document).ready(function() {
setTimeout(function(){
$("#results" ).load( "recherche.php");
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show();
var page = $(this).attr("data-page");
$("#results").load("recherche.php",{"page":page}, function(){
$(".loading-div").hide();
});
});
}, 1000);
});
<div id="results">
<div class="loading-div">
<img src="img/loader.gif">
</div>
</div>
根据评论更新
好吧,所以如果您确实想每秒刷新页面(这是非常频繁的!)那么您将需要记住当前所在的页面,以便将来的调用始终加载正确的页面。您应该使用一个变量来保存当前页面值,默认为“第 1 页”,瞧!
$(document).ready(function() {
var currentPage = 1;
var loadPage = function(page) {
$(".loading-div").show();
page = page || currentPage; // if no page parameter provided, simply reload the currentPage
$("#results").load("recherche.php",{"page":page}, function(){
currentPage = page; // once the page is loaded, update our currentPage value since this is the page we are now looking at
$(".loading-div").hide();
});
};
// Move this out of the interval - you probably don't want to set-up a click handler every time your interval is called!
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
loadPage($(this).attr("data-page"));
});
setInterval(function(){
loadPage(); // every 1 second, reload the current page
}, 1000);
loadPage(1); // initial loading of the first page
});
<div class="loading-div">
<img src="img/loader.gif">
</div>
<div id="results">
</div>
最后一件事要注意:第一次加载内容时,它将覆盖“结果”div 的内容 - 包括您的 loader.gif...我已将加载程序移至结果 div 之外,以便可以每次请求新页面时都会重新使用...
希望这有帮助!
关于javascript - Jquery自动刷新分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577706/