防止UpdatePanel之外的元素上的多个事件绑定

时间:2014-04-10 17:33:54

标签: jquery asp.net updatepanel

我有一个包含UpdatePanel内部和外部元素的webform,需要绑定javascript事件。如果我使用$(document).ready()来绑定事件,UpdatePanel之外的元素可以正常工作,但UpdatePanel内的元素会在回发时失去绑定。如果我使用pageLoad()来绑定事件,UpdatePanel内的元素可以正常工作,但外部元素会多次绑定到它们的相同事件 - 每次发生的回发一次。如何让所有元素只有一个事件的实例绑定到它们,无论它们出现在页面上的什么位置?

示例ASPX页面:

<%@ page language="C#" autoeventwireup="true" codebehind="Default.aspx.cs" inherits="WebApplication1.Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>jQuery Test</title>
    </head>

    <body>
        <form runat="server">
            <asp:scriptmanager enablepartialrendering="true" runat="server" />

            <p><a href="#">Completely unrelated link here.</a></p>

            <asp:updatepanel id="UpdatePanelTime" updatemode="conditional" runat="server">
                <contenttemplate>
                    <p>The time was last updated: <asp:literal id="LiteralTime" text="Never" runat="server" /></p>
                    <p><asp:linkbutton id="LinkButtonUpdateTime" text="Update Time"
                                       onclick="LinkButtonUpdateTimeClick" runat="server" /></p>
                </contenttemplate>
            </asp:updatepanel>
        </form>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type="text/javascript">
            function pageLoad() {
                $('a').click(function () {
                    // This click event will only occur once for the <a> in the update
                    // panel, but once-per postback + 1 for the one outside of it.
                    console.log('Link "' + $(this).text() + '" was clicked.');
                });
            }
        </script>
    </body>
</html>

代码隐藏示例:

using System;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void LinkButtonUpdateTimeClick(object sender, EventArgs e)
        {
            LiteralTime.Text = DateTime.Now.ToLongTimeString();
        }
    }
}

0 个答案:

没有答案