jQuery - 如何在使用clearInterval终止setInterval后重新启动它?
我想创建一个包含 2 个按钮的页面:“留下”和“离开”。按钮下方有一个 iFrame。第一次加载页面时,iFrame 会在 10 秒后自动开始刷新。当用户点击“STAY”按钮时,它将停止刷新。此后,如果他点击“离开”按钮,iFrame 将在 10 秒后再次开始刷新。 我正在使用这段代码:
$(document).ready(function() {
var refreshIntervalId = setInterval( "update()", 10000 );
$('#leave').click(function () {
var refreshIntervalId = setInterval( "update()", 10000 );;
})
$('#stay').click(function () {
clearInterval(refreshIntervalId);
})
});
function update(){
var url = "load.php";
$('iframe#ifrm').attr('src', url);
}
<div id="bar">
<div class= "button" id="stay">
<a>Stay</a>
</div>
<div class= "button" id="leave">
<a>Leave</a>
</div>
</div>
但它不起作用,我是否以错误的方式使用clearInterval?
I want to create a page with 2 buttons, 'STAY' and 'Leave'. There is an iFrame underneath the buttons. When the page loads for the first time, the iFrame starts refreshing automatically after 10 secs. When the user hits STAY button, it will stop refreshing. After that if he hits LEAVE button the iFrame will again start refreshing after 10 secs.
I'm using this code:
$(document).ready(function() {
var refreshIntervalId = setInterval( "update()", 10000 );
$('#leave').click(function () {
var refreshIntervalId = setInterval( "update()", 10000 );;
})
$('#stay').click(function () {
clearInterval(refreshIntervalId);
})
});
function update(){
var url = "load.php";
$('iframe#ifrm').attr('src', url);
}
<div id="bar">
<div class= "button" id="stay">
<a>Stay</a>
</div>
<div class= "button" id="leave">
<a>Leave</a>
</div>
</div>
but it doesn't work, am I using clearInterval in the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您需要将设置的间隔 id 拉到函数范围之外。
也许还对refreshIntervalId变量进行一些验证检查......
I think you need to pull the set interval id outside of the function scope.
Maybe some validation checking on the refreshIntervalId variable also...
这是一个范围问题。这意味着无论您在何处放置“var”,都定义了哪些函数可以访问该变量。如果您在所有函数之外定义变量(如 Tricker 的示例),则文档中的任何函数都可以访问该值。
Tricker 之前发布的示例:
有时整个文档不需要访问该变量,因此您希望将其放在函数中。
It's a scope issue. That means that wherever you put the "var" at defines what functions have access to the variable. If you define the variable outside of all of the functions like in Tricker's example, any function in your document has access to that value.
Tricker's example previously posted:
Sometimes the whole document doesn't need to have access to the variable, so you want to put it inside of a function.
首先,您不能在
#leave
点击函数中定义变量并在#stay
点击函数中使用它。像这样使用它:
First of all you can't define a variable in the
#leave
click function and use it in the#stay
click function.Use it like this: