Ed *_*mes 5 javascript c# asp.net updatepanel
好的:我在包含单个占位符的aspx页面上有一个UpdatePanel.
在这个占位符中,我根据某些外部条件(这是一个配置页面)附加了一个用户控件中的一个.
在每个用户控件中都有一个bindUcEvents()javascript函数,它将各种jQuery和javascript事件绑定到usercontrol中的按钮和验证器.
我遇到的问题是usercontrol的javascript未被识别.通常,updatepanel内部的javascript会在updatepanel回发时执行,但是页面中找不到这些代码(我尝试通过firebug的控制台手动运行该函数,但它告诉我它找不到该函数).
有没有人有什么建议?
干杯,艾德.
编辑:
削减(但功能)的例子:
标记:
<script src="/js/jquery-1.3.2.min.js"></script>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="Script" runat="server" />
<asp:Button ID="Postback" runat="server" Text="Populate" OnClick="PopulatePlaceholder" />
<asp:UpdatePanel ID="UpdateMe" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Postback" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Literal ID="Code" runat="server" />
<asp:PlaceHolder ID="PlaceMe" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
C#:
protected void PopulatePlaceholder(object sender, EventArgs e)
{
Button button = new Button();
button.ID = "Push";
button.Text = "push";
button.OnClientClick = "javascript:return false;";
Code.Text = "<script type=\"text/javascript\"> function bindEvents() { $('#" + button.ClientID + "').click(function() { alert('hello'); }); } bindEvents(); </script>";
PlaceMe.Controls.Add(button);
}
Run Code Online (Sandbox Code Playgroud)
即使代码存在于页面上,您也会看到按钮没有弹出警告消息.
EDIT2:
好吧,只是为了说清楚,生产代码比绑定到文字的单个函数复杂得多,并且包含大量的
<%= Control.ClientID %>
Run Code Online (Sandbox Code Playgroud)
一些代码将很难分解为非特定函数,并且毫无意义,因为它们每个都只在一个地方使用(我们说的是非常具体的验证和奇怪的弹出触发器+一些逻辑).
摆脱Literal控件并使用ScriptManager注册脚本.你正在做的事情由于同样的原因不起作用
window.document.getElementById('someId').innerHtml = "<script type=\"text/javascript\">alert('hey');</script>";
Run Code Online (Sandbox Code Playgroud)
不起作用.试试这个:
protected void PopulatePlaceholder(object sender, EventArgs e)
{
Button button = new Button();
button.ID = "Push";
button.Text = "push";
button.OnClientClick = "return false;";
string script = "function bindEvents() { $('#" + button.ClientID + "').click(function() { alert('hello'); }); } bindEvents();";
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(SomeClass), Guid.NewGuid().ToString(), script, true);
PlaceMe.Controls.Add(button);
}
Run Code Online (Sandbox Code Playgroud)
RegisterClientScriptBlock的参数可能需要改变,但你明白了.
要在更新面板触发后重新运行一些js,我总是使用它
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
function(sender, args) {
//update whatever here
});
Run Code Online (Sandbox Code Playgroud)
此外,如果您对更新面板中的元素有任何引用,您也可以刷新该函数中的那些变量,否则您将拥有不起作用的旧引用.