为什么我的文档正文onload事件不断发生?

Why does my document body onload event occurs continously?

我有一个 javascript 函数,它会在按钮上引发单击事件,从而激活代码隐藏中的函数。我希望这个 click/function 在页面首次加载时发生一次,但是我无法弄清楚为什么 onload 事件似乎连续发生。

Figure1.aspx代码如下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Figure1.aspx.cs" Inherits="Figure1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Page 1</title>
</head>

<body style='margin: 0px; overflow: hidden;' onload="getLocation()">
    <script>
        function getLocation() {
            document.getElementById('insertMyLocationButton').click();
        }
    </script>

    <form id="form1" runat="server">
        <div>
            <asp:Button ID="insertMyLocationButton" runat="server" Text="insertMyLocation" 
                onclick="insertMyLocation2" ClientIDMode="Static" style="display:none;"/>
            <p><asp:Literal runat="server" Id="insertResult">1</asp:Literal></p>    
       </div>
    </form>

</body>
</html>

我的Figure1.aspx.cs如下

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Figure1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void insertMyLocation2(object sender, EventArgs e)
    {
        insertResult.Text = Convert.ToString(Convert.ToInt16(insertResult.Text)+1);
    }
}

这段代码中的服务器端函数insertMyLocation2更新了id为inserResult的段落标签中的字符串,可以看出它是不断更新的,即使唯一的调用应该来自onload事件。

我希望只有一个 onload 事件调用。

感谢您帮助新手。

我会像这样处理代码隐藏文件中的 "click":

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "",
                                           "<script language=javascript>getLocation();</script>");
    }
}

protected void insertMyLocation2(object sender, EventArgs e)
{
    insertResult.Text = Convert.ToString(Convert.ToInt16(insertResult.Text) + 1);
}

然后你需要从正文标签中删除:

 onload="getLocation()"

 <body style='margin: 0px; overflow: hidden;'>

然后页面应该显示 2 并停止。

上面的评论中回答了为什么它会这样做。 希望这有帮助。