开发者

JQuery effects on dynamically created controls inside ASP.NET AJAX update panel

Hello StakOverflowians! Wondering whether someone could help with this.

I have a dynamically created tag inside an AJAX update panel. Upon clicking the tag, I am trying to (for the time being) display an alert using JQuery. The problem is that the alert doesn't get displayed when the tag is generated dynamically, however, if I declare the tag statically in .aspx, then it works. Here is the code:

   protected void Button_Click(object sender, EventArgs e){
       HtmlAnchor htmlA = new HtmlAnchor();
       htmlA.ID = "hidden_link";
       PlaceHolder1.Controls.Add(htmlA);

       string javaScriptFunction =
          "jQuery(document).ready(function() {" +
              "$(function () {" +
                  "$(\"a[i开发者_StackOverflow社区d$='hidden_link']\").click(function () {" +
                      "alert('Alert: Hello from jQuery!');" +
                  "});" +
              "});" +
          "}";

       ScriptManager.RegisterStartupScript(this, 
                                           this.GetType(), 
                                           "myScript", 
                                           javaScriptFunction, 
                                           true); 
   }

and on .aspx, I have:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </ContentTemplate>
</asp:UpdatePanel>

<script language="javascript" type="text/javascript">
    function pageLoad() {
        jQuery(document).ready(function() {
        $("a[id$='hidden_link']").click(function() {
                alert("Alert: Hello from jQuery!");
            });
        });
    } 
</script>

What should I do to get the alert working for dynamically created controls inside the PlaceHolder1? Any help will be most appreciated.

Thanks, Ali


If you're button click is running in an async post back, you're not actually reloading the page. So, the $(document).ready() method won't get called.

To solve your problem, just remove the call.

string javaScriptFunction = "$(\"a[id$='hidden_link']\").click(function () { alert('Alert: Hello from jQuery!'); });";

Or alternatively, you may find jQuery's live() function more suitable for attaching handlers to elements that are created dynamically

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜