[英]Cancel javascript redirection on mouse click event
我想取消由javascript函數啟動的重定向。 javascript將在5秒鍾內重定向到主頁,並顯示為錯誤消息。 我想通過單擊錯誤消息來取消重定向。 請幫忙。
PHP代碼:
<div id="error">
<?php
//redirect
if (isset($_GET['err'])){
if ($_GET['err'] == 1){
echo "You are successfully logged out. You will be redirected to the home page in <strong><span id = 'seconds'> 5 </span> </strong> seconds.";
}elseif($_GET['err'] == 0){
echo "Your session has been expired. Please login again.!";
}
}
?>
</div>
使用Javascript:
<script>
var seconds = 5;
var err = <?php echo $_GET['err'] ; ?>;
if (err == 1){
setInterval(
function(){
if (seconds <= 1) {
window.location = 'http://****.***.***.***/***';
}
else {
document.getElementById('seconds').innerHTML = --seconds;
}
},
1000
);
}
</script>
實際上,您實際上是在嘗試停止setInterval,可以通過先命名它,然后在所需的條件下清除它來輕松完成此操作。
var redirInt = setInterval(function() {
// etc.
},5000);
還有取消行
clearInterval(redirInt);
var tId; // create a global var (or put it in a managed scope)
$(function() { // jquery onload
tId = setInterval(function() { ... },5000); // or use timeout if no counter
$("#errordiv").on("click",function() {
clearInterval(tId); // clear it
});
});
setInterval
返回其創建的計時器的ID,以便您可以使用clearInterval
取消它。
您可以使用如下形式:
var timer;
$(document).ready(function() {
timer = setInterval(function() {...}, 1000);
$('#error').click(function() {
clearInterval(timer);
});
});
嘗試這個:
<script>
var seconds = 5;
var err = <?php echo $_GET['err'] ; ?>;
var redir = null;
if (err == 1){
var redir_interval = setInterval(
function(){
if (seconds <= 1) {
redir = window.location = 'http://****.***.***.***/***';
}
else {
document.getElementById('seconds').innerHTML = --seconds;
}
},
1000
);
}
function cancel_redir() {
redir = null;
clearInterval(redir_interval);
}
</script>
<div id="error" onclick="cancel_redir();">
You are successfully logged out. You will be redirected to the home page in <strong><span id = 'seconds'> 5 </span> </strong> seconds.
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.