有没有更好的方式来获得的ClientID的进入外部JS文件? [英] Is there a better way to get ClientID's into external JS files?

查看:97
本文介绍了有没有更好的方式来获得的ClientID的进入外部JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已经问过,但我发现不同的方式来获得外部JS文件控件的引用,但我不知道这将如何往下走整体速度方面。

I know this has been asked before, but I've found a different way to get references to controls in external JS files but I'm not sure how this would go down in terms of overall speed.

我的code是

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());
        }
    }

这是我可以引用aspx页面的ID在我的JS文件。

This was I can reference the id of the aspx page in my JS files.

任何人都可以看到任何缺点做事这种方式?我只使用外部JS文件开始。之前,一切都写进了用户控件本身。

Can anyone see any drawbacks to doing things this way? I've only started using external JS files. Before everything was written into the UserControl itself.

推荐答案

那么,该方法只能使用一次,在每一个页面中使用,所以如果你是从一个用户控件调用它,这意味着你可以永远把两个那些在同一页上的用户控件

Well, the method can only be used once in each page, so if you are calling it from a user control that means that you can never put two of those user controls on the same page.

您可以存储在列表中的控件引用,直到preRender事件,然后把他们都在页面头部的脚本标签。这样,你可以调用方法不止一次,和所有客户端ID都放在同一个脚本标记。

You could store the control references in a list until the PreRender event, then put them all in a script tag in the page head. That way you can call the method more than once, and all client IDs are put in the same script tag.

是这样的:

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));
}

这篇关于有没有更好的方式来获得的ClientID的进入外部JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆