在警报框上设置超时时间

SetTimeOut on Alert Box

本文关键字:设置 超时 时间      更新时间:2023-09-26

感谢您在这个论坛上提供的每一点帮助。我代表其他人,向你表示感谢,并希望你明白这一点。

与此同时,我有一个任务需要解决。设置警报框的超时时间。也就是

<?php
echo '
<script type="text/javascript">
var t = setTimeOut(5000); //5secs
alert("Your score is: ". $score. '.");
if(t === TRUE){
//clear alert box
this.alert.OK = true;
window.location = "index.php";
}
</script> ';
?>

请不要介意我的伪代码。这是我理解javascript工作的最错误的方式。

我知道一切皆有可能——总会有办法绕过挑战。但我并没有真正的解决方案。我要把它扔给屋子里的大师们。

感谢期待,我们将一起度过这个挑战。我永远是你忠实的朋友。

警告不能超时。这是一个低级的JavaScript结构,它创建了一个本地应用程序对话框,需要在它被销毁之前由用户确认。如果您希望向用户"抛出数据",则必须使用实际的HTML对话框库(或者您自己创建)。

同样,不要使用alert()。当我们没有其他选择时,它很棒,但现在您使用console.log(...)来简单地记录数据(任何数据)。)到开发工具控制台(每个浏览器都有一个),并且有一百万个JS库可以为用户生成漂亮的模态(现在唯一合法使用警报的是强制停止整个页面处理线程……我一时想不出一个你为什么要那样做的理由。

也就是说,你给的PHP代码完全没有意义。它实际上是一个.js文件,扩展名为.php。删除这些php标签,将其保存为。js,并仅<script src="thatfile.js"></script>的东西。不要让PHP做那些你根本不需要PHP做的事情。

浏览器不允许在其警报上超时,至少目前是不可能的。但这里有一种可能的解决方法。用html和css创建一个消息框。

php:

<?
  ... what required to compute/fetch the score
?>
<html>
  <head>
   <meta http-equiv="refresh" content="5;index.php"/><!-- redirect after 5 secs -->
  </head>
  <body>
   <div class="message-box">
    <label>Your score is:<?$score?></label>
   </div>
  </body>
</html>

meta标签将告诉浏览器在5秒后重定向到给定的页面。同时,页面以php变量给出的动态分数显示给用户。

EDIT:如果你不被允许使用meta标签,那么试试这个

<?
  ... what required to compute/fetch the score
?>
<html>
  <body>
   <div class="message-box">
    <label>Your score is:<?$score?></label>
   </div>
  </body>
  <!-- not a good practice to put tag here, but it will do the trick to redirect after page is loaded-->
  <script>
    setTimeout(function(){
       location.assign("index.php");//<-- where to redirect
    }, 5000); //<-- redirect after 5 secs
  </script>
</html>

是否可以这样做:

var t = setTimeOut(function(){
alert("Your score is: ". $score. '.");
},5000); //5secs

?