[英]Click event of control in dynamically loaded usercontrol not firing in .js file
我在更新面板中有一個帶占位符的aspx頁面。 根據頁面上下拉菜單的值,用戶控件將附加到占位符。 用戶控件正確加載,但似乎未觸發按鈕的click事件。 我在.js文件中放置了一個斷點,但是它從未進入js函數。 不確定是否已加載JavaScript。
aspx頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page.aspx.cs" Inherits="UserControlTest.Page" %>
<%@ Register Src="~/TestUserControl.ascx" TagPrefix="uc1" TagName="TestUserControl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/testUserControl.js"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
<div>
<h4>This is the page</h4>
<div class="form-group">
<label class="col-md-5 control-label" for="selUserControl">Enquiry Type <span class="glyphicon glyphicon-asterisk pull-right" style="color:red"></span> </label>
<div class="col-md-7">
<asp:DropDownList ID="selUserControl" CssClass="form-control reqrd" runat="server" OnSelectedIndexChanged="selUserControl_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
</div>
</div>
<div id="divUserControl">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="phUserControl" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="selUserControl" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</form>
</body>
</html>
aspx.cs頁面:
protected void selUserControl_SelectedIndexChanged(object sender, EventArgs e)
{
TestUserControl uc = (TestUserControl)LoadControl("~/TestUserControl.ascx");
uc.ID = "ucUserControl";
phUserControl.Controls.Add(uc);
}
.ascx頁面:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestUserControl.ascx.cs" Inherits="UserControlTest.TestUserControl" %>
<div>
<h4>This is the User Control</h4>
</div>
<div class="form-group">
<div class="col-md-7">
<input type="button" id="btnPress" class="btn" value="Press!" />
</div>
</div>
.js文件:
$(document).ready(function () {
$("#btnPress").click(function () {
alert('Hi There from User Control');
});
});
在運行js
時,頁面上#btnPress
不存在(或者至少原始#btnPress
不存在。@ DelightedD0D是正確的。我會研究使用事件委托並將它們附加到您的文檔中。您可以根據需要附加/分離盡可能多的#btnPress
方式,您的點擊將冒泡記錄#btnPress
處理。
$(document).on('click', '#btnPress', function(){
alert('Hi There from User Control');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.