【发布时间】:2019-08-26 10:54:52
【问题描述】:
我正在为我的老师创建一个基于引导程序的网站作为一个小项目,但我的计时器有问题。所以这个网站是用瓦片构建的,当点击它时,会触发填充模态的 ajax 函数,并在最后显示模态。 问题在于模式中的计时器。它仅在每第二次显示模态时才起作用。控制台中没有错误或任何有用的东西。 这是我的 php 输出模式:
echo "<div id='timer_out' onclick='timer_start()' style='font-size: calc(35px + 5vw); font-weight: bold;'>00:00:00:000</div>";
echo "<span>Podnieś spację, aby włączyć/wyłączyć timer</span>";
echo '
<script>
out=$("#timer_out");
counter="";
running=false;
function timer_start(){
if(running){
running=false;
clearInterval(counter);
return;
}
running=true;
time=0;
start = new Date;
counter=setInterval(function(){
console.log("test")
time=new Date - start;
h=Math.floor(time/1000/60/24);
min=Math.floor(time/1000/60-h*1000*60*24);
sec=Math.floor(time/1000-min*60-h*1000*60*24);
ms=Math.floor(time-sec*1000-min*60*1000-h*1000*60*24);
if(h<10) h="0"+h;
if(min<10) min="0"+min;
if(sec<10) sec="0"+sec;
if(ms<10) ms="00"+ms;
else if(ms<100) ms="0"+ms;
out.text(h+":"+min+":"+sec+":"+ms);
}, 1);
}
function timer_stop(){
running=false;
clearInterval(counter);
}
document.addEventListener("keyup", function(event){
if (event.code!="Space") return;
timer_start();
});
$("#mainModal").on("hide.bs.modal", function (e) {
timer_stop();
});
$("#mainModal").on("show.bs.modal", function (e) {
timer_stop();
});
</script>
';
我发现当我第二次触发计时器时(所以它不起作用)函数 timer_start() 会启动,但没有创建 Interval,所以对我来说更令人困惑:/
如果对你有帮助,这是我的 ajax:
modal_body=$(this).find('div.modal-body')
$.ajax({
type: 'post',
url: 'php/getModal.php',
data: {
id: '-3'
}
}).done(function(returned){
modal_body.html(returned);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('error'+'\n'+jqXHR+'\n'+textStatus+'\n'+errorThrown);
}).always(function(){
});
更有趣的是,在手机上,它可以完美运行ヽ(。_°)ノ
【问题讨论】:
标签: jquery ajax modal-dialog setinterval