【发布时间】:2017-02-11 20:07:21
【问题描述】:
我创建了一个简单的 ASP.Net html 页面。我想进行密码检查,只有在页面最初加载时,我使用脚本进行了检查,并将标签 onload 分配给 body。问题是,每次按下按钮都会触发密码检查。为什么会发生这种情况?如何仅在打开页面时执行密码检查? 提前致谢。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FotoDiClasse.aspx.cs" Inherits="FotoDiClasse" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Choose your sweatshirt</title>
<!-- password control -->
<script>
var password;
var pass1 = "1234";
var firstTime = true;
function checkPassword()
{
if (firstTime)
firstTime = false;
password = prompt("Enter password to access the site", '');
if (password != pass1) window.location = "http://www.google.com";
}
</script>
</head>
<body onload="checkPassword()">
<form id="form1" runat="server">
<div>
<asp:Button ID="CreateButton" runat="server" Text="Create" Width="240px" OnClick="CreateButton_Click" />
<asp:Button ID="SendButton" runat="server" Text="Send" Width="240px" OnClick="SendButton_Click" />
</div>
</form>
</body>
</html>
这个“第一次”标志不起作用
【问题讨论】:
-
应该注意
password = prompt...将运行无论firstTime是否为真,因为您没有在if 语句周围使用大括号。仅仅因为你缩进了代码,并不意味着代码不会运行。