我提出了以下代码,它允许用户在将他们重定向离开页面之前查看嵌入了电影的页面 30 秒。此外,他们还可以单击链接来隐藏带有倒计时的 div。我需要帮助的是,如果单击该链接,则取消重定向(阻止其发生),以便用户可以继续观看完整的电影。预先感谢您的帮助!
Javascript:
<script type="text/javascript">
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").show();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
HTML:
<div id="my-timer" class="slidingDiv">
You have <b id="show-time">30</b> seconds to decide on this movie.
<a href="#" class="show_hide">Yes, I want to watch this one!</a>
</div>
最佳答案
setInterval
返回一个值,您可以使用 clearInterval
取消间隔计时器。 。所以:
$(function(){
// +--- Remember the value from `setInterval
// |
// v
var timerHandle = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
// + Hook up a handler for the link that uses the handle to clear it
// |
// v
$("selector_for_the_link").click(function() {
clearInterval(timerHandle);
timerHandle = 0;
});
});
请注意,我已将变量放入您的 ready
中函数,因此它不是全局的。
离题:您不需要或不想使用eval
在上面(事实上,你实际上根本不想使用 eval
来做任何事情)。如果要解析字符串以生成数字,请使用 parseInt
(并且没有任何理由评估像 1
这样的文字)。所以这一行:
var updateTime = eval(timeCounter)- eval(1);
变成了
var updateTime = parseInt(timeCounter, 10) - 1;
(10
表示字符串是十进制的,例如以 10 为基数。)
关于javascript - 如果按下按钮,如何终止 JavaScript 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6421166/