我在更新面板中有一个带占位符的aspx页面。用户控件根据页面上下拉列表的值附加到占位符。用户控件正确加载,但似乎按钮的单击事件未触发。我在.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');
});
});
答案 0 :(得分:1)
当您运行js
时,页面上不存在#btnPress
(或者至少原始#btnPress
没有。@ DelightedD0D是对的。我会考虑使用事件代理并将它们附加到您的文档。这样您就可以根据需要附加/分离尽可能多的#btnPress
,并且您的点击将冒泡到文档并由代表处理。
$(document).on('click', '#btnPress', function(){
alert('Hi There from User Control');
});