用/ if else确认声明

时间:2014-09-21 11:20:36

标签: javascript jquery html

我正在尝试创建一个页面,在用户进入页面10秒后弹出确认框。它说“你想离开这个页面吗?”如果用户单击“确定”,则会将用户传送给Google。如果用户单击“取消”,将弹出一个警告,说“确定。您可以留下来”。这只是一个练习。

HTML:

<html>
<head>
</head>
<body>
<h1>Something.</h1>
<ul>
<li>Info...</li>
<li>More...</li>
<li>Yet More...</li>
</ul>
<script type="text/javascript" src="confirm.js"></script>
</body>
</html>

JavaScript的:

function stayonPage(){
var is_sure = window.confirm("Do you want to leave this page?");
}
var waittime = window.setTimeout("stayonPage()",10000);

if(is_sure=false;)
{window.alert("OK. You can stay.");}
else
{window.location="http://www.google.com";}

到目前为止,网页会显示一秒钟,然后在未显示确认框的情况下转到Google。

4 个答案:

答案 0 :(得分:1)

那是因为脚本继续执行。

{10}后,setTimeout将弹出问题,因为您在十秒钟后将其设置为回调函数。 但是 - 脚本在此期间继续,发现is_sure变量未定义,因此转到else语句。

您可以将if语句放在stayonPage函数内,该函数在10秒后执行该函数。

答案 1 :(得分:0)

如果/ else阻止 stayonPage函数,你需要进行重定向,并使用比较运算符而不是赋值:

function stayonPage(){
    var is_sure = window.confirm("Do you want to leave this page?");
    if(is_sure == false) // here you need to use == instead of = and no semi-colon
        {window.alert("OK. You can stay.");}
    else
        {window.location="http://www.google.com";}
}
var waittime = window.setTimeout("stayonPage()",10000);

整个事物的优化版本如下所示:

setTimeout(function(){
    if (!confirm("Do you want to leave this page?"))
        alert("OK. You can stay.");
    else
        window.location="http://www.google.com";
}, 10000);

在此处查看:http://jsfiddle.net/un52w63c/(注意,重定向不适用于jsfiddle)

答案 2 :(得分:0)

几个问题:

  • 您不等待测试答案
  • 您正在分配is_sure而不是比较

&#13;
&#13;
function stayonPage(){
var is_sure = window.confirm("Do you want to leave this page?");
// move it inside the function
if(is_sure==false) // compare, don't assign
{window.alert("OK. You can stay.");}
else
{window.location="http://www.google.com";}
}
setTimeout(stayonPage, 10000);
// don't need to keep a reference, and don't need to use window
// we can just reference the function instead of using implicit eval
&#13;
&#13;
&#13;

答案 3 :(得分:0)

function stayonPage(){
   var is_sure = window.confirm("Do you want to leave this page?"); 

/* is_sure is scoped inside this function it is not a global and
can not be used from a different global function */

/* is_sure=false sets is_sure to false and always returns false and
because it is already a true or false so no condition operation is required */

   if(is_sure) 
     {window.location="http://www.google.com";
   }
   else
     {window.alert("OK. You can stay.");
   }
}



var waittime = window.setTimeout("stayonPage()",10000);
/* 
I assume this will be replace by something more logical,
It will ask if you are sure you wanted to leave without the user
indicating he wanted to leave. 
*/