setTimeOut不工作(jQuery)
我有一个div“pushBtns”和一个id为“showPushBtns”的锚定标记,“pushBtns”将隐藏在pageload上,并在pageload后5秒内显示。但是,如果用户单击锚id“showPushBtns”,则应停止“timedShow()”函数,并显示div“pushBtns”。定时显示隐藏功能工作正常,但我无法使“clearTimeout”正常工作。请帮忙 我是jQuery的初学者setTimeOut不工作(jQuery),jquery,Jquery,我有一个div“pushBtns”和一个id为“showPushBtns”的锚定标记,“pushBtns”将隐藏在pageload上,并在pageload后5秒内显示。但是,如果用户单击锚id“showPushBtns”,则应停止“timedShow()”函数,并显示div“pushBtns”。定时显示隐藏功能工作正常,但我无法使“clearTimeout”正常工作。请帮忙 我是jQuery的初学者 <script type="text/javascript"> $(document
<script type="text/javascript">
$(document).ready(function() {
var theButtons = $("#pushBtns");
theButtons.hide();
function showIt(){
theButtons.show(1000);
}
function timedShow() {
var timer = setInterval(function() {showIt();},5000);
}
timedShow();
$('#showPushBtns').click(function(){
clearTimeout(timer);
});
});
</script>
使用
clearInterval
,而不是clearTimeout
或者,使用
setTimeout
和cleartimout
应该更适合您的需要。为什么要每5秒调用showIt
?您的计时器变量是timedShow函数的本地变量-使其成为全局变量,您需要使用clearInterval
$(document).ready(function () {
var timer;
var theButtons = $("#pushBtns");
theButtons.hide();
function showIt() {
theButtons.show(1000);
}
function timedShow() {
timer = setInterval(function () {
showIt();
}, 5000);
}
timedShow();
$('#showPushBtns').click(function () {
clearInterval(timer);
});
});
clearTimeout(timer)
只是清除计时器,这样函数就永远不会运行。因此,您需要在清除计时器后执行showIt()
$('#showPushBtns').click(function()
{
clearTimeout(timer);
showIt();
});
编辑:还注意到您正在使用
setInterval
。你的意思是在那里使用setTimeout
吗?setInterval和clearTimeout与jQuery无关……你的小提琴中有很多错误,重复的ID,错误的赋值。下面是一个工作示例:
$('#showPushBtns').click(function()
{
clearTimeout(timer);
showIt();
});