HTML onload脚本触发了太多次?

时间:2017-01-25 18:51:30

标签: html asp.net onload

我创建了一个简单的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>

这是&#34;第一次&#34;旗帜不起作用

2 个答案:

答案 0 :(得分:0)

这是因为每次按下按钮都会加载页面并调用onload()方法,因此每次调用该方法时都会这样。

要解决此问题,您需要设置某种功能,以检查您的网页是否第一次加载或不执行此操作,您可以使用cookie来存储该会话。

<%@ 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>
    <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" onblur="checkPassword()"/>
    </div>
    </form>
</body>
</html>

答案 1 :(得分:0)

它被称为PostBack。每次按下按钮时,Page都会执行Form Post(PostBack)。这意味着页面已重新加载。

使用下面的代码段,您只能在首次加载页面时调用JavaScript函数。

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "runScript", "alert('This is not a PostBack');", true);
    }
}