Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我的文档正文onload事件持续发生?_Javascript_Asp.net_Onload_Code Behind_Document Body - Fatal编程技术网

Javascript 为什么我的文档正文onload事件持续发生?

Javascript 为什么我的文档正文onload事件持续发生?,javascript,asp.net,onload,code-behind,document-body,Javascript,Asp.net,Onload,Code Behind,Document Body,我有一个javascript函数,它会在按钮上引发单击事件,从而激活代码隐藏中的一个函数。我希望这个点击/函数在页面第一次加载时发生一次,但是我不明白为什么onload事件似乎持续发生 图1.aspx代码如下所示 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Figure1.aspx.cs" Inherits="Figure1" %> <!DOCTYPE html> <html xmlns="htt

我有一个javascript函数,它会在按钮上引发单击事件,从而激活代码隐藏中的一个函数。我希望这个点击/函数在页面第一次加载时发生一次,但是我不明白为什么onload事件似乎持续发生

图1.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>

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

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

感谢您帮助一位新手。

我会像这样处理代码隐藏文件中的“单击”:

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);
}
受保护的无效页面加载(对象发送方,事件参数e)
{
如果(!IsPostBack)
{
ClientScript.RegisterStartupScript(this.GetType(),“”,
“getLocation();”;
}
}
受保护的void insertMyLocation2(对象发送方,事件参数e)
{
insertResult.Text=Convert.ToString(Convert.ToInt16(insertResult.Text)+1);
}
然后,您需要从body标记中删除:

 onload="getLocation()"

 <body style='margin: 0px; overflow: hidden;'>
onload=“getLocation()”
然后页面应该显示2和停止

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

因为单击按钮后,它将执行回发并重新加载页面。这将再次调用onload函数,并将继续无限循环。
 onload="getLocation()"

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