~/ equivalent in javascript

后端 未结 12 1960
萌比男神i
萌比男神i 2020-12-12 19:11

Any smart way of doing a \"root\" based path referencing in JavaScript, just the way we have ~/ in ASP.NET?

12条回答
  •  -上瘾入骨i
    2020-12-12 20:06

    In the PreRender of your .NET base page, add this:

     protected override void
     OnPreRender(EventArgs e) {
         base.OnPreRender(e);
    
         if (Page.Header != null)
         {
             //USED TO RESOLVE URL IN JAVASCRIPT
             string baseUrl = String.Format("var baseUrl='{0}';\n", 
               HttpContext.Current.Request.ApplicationPath);
             Page.Header.Controls.Add(new LiteralControl(String.Format(Consts.JS_TAG,
               baseUrl)));
         }
    }
    

    Then in your global JavaScript function, add the following:

     function resolveUrl(url) {
       if (url.indexOf("~/") == 0) {
         url = baseUrl + url.substring(2);
       }
     return url; }
    

    Now you can use it like this:

     document.getElementById('someimage').src = resolveUrl('~/images/protest.jpg');
    

    May be a little much for some projects, but works great for full fledged applications.

提交回复
热议问题