我知道之前已经问过这个问题,但是我发现了一种不同的方法来获取外部JS文件中控件的引用,但我不确定这会如何在整体速度方面下降.
我的代码是
public static void GenerateClientIDs(Page page, params WebControl[] controls) {
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in controls) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
if (!page.ClientScript.IsClientScriptBlockRegistered("Vars")) {
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Vars", script.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
这是我可以在我的JS文件中引用aspx页面的id.
任何人都可以看到以这种方式做事的任何缺点吗?我刚开始使用外部JS文件.在将所有内容写入UserControl本身之前.
好吧,该方法只能在每个页面中使用一次,因此如果您从用户控件调用它,则意味着您永远不能将其中两个用户控件放在同一页面上。
您可以将控件引用存储在列表中,直到 PreRender 事件发生,然后将它们全部放入页面头部的脚本标记中。这样您就可以多次调用该方法,并且所有客户端 ID 都放在同一个脚本标记中。
就像是:
private const string _key = "ClientIDs";
public static void GenerateClientIDs(params WebControl[] controls) {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
if (items == null) {
page.PreRender += RenderClientIDs;
items = new List<WebControl>();
}
items.AddRange(controls);
HttpContext.Current.Items[_key] = items;
}
private static void RenderClientIDs() {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in items) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
page.Head.Controls.Add(new LiteralControl(script));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2262 次 |
| 最近记录: |