在JavaScript中设置变量不起作用

时间:2013-11-13 09:06:37

标签: javascript login

我制作了这个小JavaScript:

<script type="text/javascript">
if(perm == 0)
{
var perm = 0;
var password = "showrocks69";
var pass = prompt("[Login] Type in the Admin CP Password:","");
if(pass==password)
{
perm = 1;
window.location = "http://cod5showtime.url.ph/acp.html";
}
else
{
alert("[Error] Invalid Password!");
window.location = "http://cod5showtime.url.ph/";
}
}
</script>
<script type="text/javascript">
function acpLogout()
{
var perm = 0;
alert("[Log Out] Logged out from Administrator Account");
window.location = "http://cod5showtime.url.ph/";
}
</script>

这个按钮:

<button class="btn" onClick="acpLogout()">Log Out</button>

我希望当有人点击退出时,该人将被注销,而'perm'变量将设置为0.我已尝试完成此操作,如上所示,它无法正常工作。任何想法?

2 个答案:

答案 0 :(得分:1)

当您再次访问该页面时,会创建一个全新的JavaScript上下文,其中包含一个新的'perm'变量,该变量最初未定义,然后是您的代码。没有办法让变量在页面重新加载时生效。

然而,您可以做的是将您想要的信息(无论用户是否记录)保存在更永久的媒介中(如cookie或某些HTML5存储):

// first thing you do get the variable from localStorage
var perm = localStorage.getItem('loggedState');

if (perm === 'loggedOut') {
  // code for logged out
} else {
  // code for logged in
}

function logout() {
  perm = 'loggedOut';
  // save the variable to localStorage
  localStorage.setItem('loggedState', perm);
}

function login() {
  perm = 'loggedIn';
  // save the variable to localStorage
  localStorage.setItem('loggedState', perm);
}

请注意,我绝不认为这种方法可以处理角色/权限,但它确实解决了OP的直接问题。

答案 1 :(得分:0)

你可以这样试试:

            <script type="text/javascript">
            function acpLogout()
            {
            var perm = 0;
            alert(perm);
            alert("[Log Out] Logged out from Administrator Account");



            if(perm == 0)
            {
            var perm = 0;
            var password = "showrocks69";
            alert(password);
            var pass = prompt("[Login] Type in the Admin CP Password:","");
            if(pass==password)
            {
            perm = 1;
            window.location = "http://cod5showtime.url.ph/acp.html";
            }
            else
            {
            alert("[Error] Invalid Password!");
            window.location = "http://cod5showtime.url.ph/";
            }
            }
            }
            </script>
            <br />


            <button class="btn" onClick="acpLogout()">Log Out</button>