使用jquery重置setInterval函数
这是我的代码:使用jquery重置setInterval函数,jquery,html,timer,refresh,Jquery,Html,Timer,Refresh,这是我的代码: $(document).ready(function() { $('#mid_select').live('click', function(e){ $('#middle').load( $(this).attr('href') + ' #middle'); var page = $(this).attr("rel"); alert(page); if (page == 'mywall'){
$(document).ready(function() {
$('#mid_select').live('click', function(e){
$('#middle').load( $(this).attr('href') + ' #middle');
var page = $(this).attr("rel");
alert(page);
if (page == 'mywall'){
var auto_refresh = setInterval(function () {
$('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow");}, 5000);
} else {
clearInterval(auto_refresh);
}
e.preventDefault();
});
});
我想做的是,如果用户点击一个id为
#mid_select
且rel
属性等于“mywall”的链接,然后每隔5秒刷新#bottom_middle
div,但是如果用户点击的链接rel
属性不等于“mypage”然后不要每5秒刷新一次#bottom_middle
div。无法找到如何完成此操作,请帮助任何人?您必须在单击处理程序(使用var
)外部存储对setInterval
s timeout的引用。此外,您还必须确保每次循环的最大间隔为一个。如下所示,调整后的代码符合这些标准:
$(document).ready(function() {
var auto_refresh = false; // Store this variable OUTSIDE the click handler
$('#mid_select').live('click', function(e){
var $this = $(this);
$('#middle').load( $this.attr('href') + ' #middle');
var page = $this.attr("rel");
alert(page);
if (page == 'mywall'){
// Check whether an instance is already running...
if (auto_refresh === false) {
// NO var, because we use the auto_refresh var in the parent scope
auto_refresh = setInterval(function () {
$('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow");
}, 5000);
} else {
// Clear interval, and explicitly set it to true
clearInterval(auto_refresh);
auto_refresh = false;
}
e.preventDefault();
});
});
在JSFIDLE上发布html。您不需要这个部分:否则{clearInterval(auto_refresh)}是的,Rob,谢谢,这工作非常好!一件小事,必须添加一个
}
来结束if(auto_refresh==false){
语句。再次感谢。