如果按下取消,关闭标签/重定向?

时间:2016-07-30 21:18:30

标签: javascript

我正在创建一个需要密码才能访问它的网站,但是一旦密码提示启动,就很难(不是用户友好的)返回。密码的目的是防止用户看到页面和页面源。
这是我到目前为止所拥有的:

        do{
            $('html').hide();  //hiding html with jQuery
            var pass = "password";  //setting password
            var selection = prompt("Enter password", "");  //prompting for password
            if(selection == "cancel"){
                window.location.href = "http://www.example.com/";
            };  //trying (unsuccesfully) to make the page redirect if user answers "cancel"
        } while(selection!=pass);

1 个答案:

答案 0 :(得分:-1)

来自https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

If the user clicks the Cancel button, this function returns null.

所以,

do{
  $('html').hide();
  var pass = "password";
  var selection = prompt("Enter password", "");
  if(selection === null) {
    window.location.href = "http://www.example.com/";
    break;
  };
} while(selection !== pass);

您需要break语句,因为如果仍有代码在运行,浏览器将不会重定向,例如while循环。