【发布时间】:2015-02-27 04:58:25
【问题描述】:
我在更新面板中有一个带有占位符的 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');
});
});
【问题讨论】:
-
您需要使用事件委托将函数绑定到动态添加的元素。查看 jquery 的 on() 方法,例如 $(document).on('click', '#btnPress', function(){ ..... Code here});
-
谢谢,就像一个魅力。由于这是一条评论,我无法将其标记为答案。 :(
标签: javascript jquery asp.net