Javascript 外部文件中Javascript中的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2188218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Relative Paths in Javascript in an external file
提问by Nate
So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
所以我正在运行这个 javascript,一切正常,除了背景图像的路径。它适用于我的本地 ASP.NET Dev 环境,但在部署到虚拟目录中的服务器时它不起作用。
This is in an external .js file, folder structure is
这是在一个外部 .js 文件中,文件夹结构是
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
那么这是包含js文件的地方
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg'and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
我试过使用'/Images/filters_collapse.jpg',但也不起作用;但是,如果我使用'../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
基本上,我希望具有与 ASP.NET tilda -- 相同的功能~。
update
更新
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
外部 .js 文件中的路径是相对于它们所包含的页面还是 .js 文件的实际位置?
回答by Juraj Blahunka
JavaScript file paths
JavaScript 文件路径
When in script, paths are relative to displayed page
在脚本中时,路径是相对于显示页面的
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
为了让事情更容易,你可以打印出一个简单的 js 声明,并在你的脚本中使用这个变量:
Solution, which was employed on StackOverflowaround Feb 2010:
2010 年 2 月左右在StackOverflow 上使用的解决方案:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head />section
如果你访问该页面在2010年左右,你可以只看看StackOverflow上的HTML源代码,你会发现这个坏蛋的单行[格式化〜3行:)]在<head />部分
回答by schory
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
通过解析引用它的 'src' 属性的 DOM,在运行时使用 jQuery 获取 javascript 文件的位置:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
(假设您的 javascript 文件名为“example.js”)
回答by PHPst
A proper solution is using a css class instead of writing src in js file. For example instead of using:
正确的解决方案是使用 css 类而不是在 js 文件中编写 src。例如,而不是使用:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
用:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
并在页面中加载的 css 文件中写入:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
回答by Pekka
Good question.
好问题。
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
在 CSS 文件中时,URL 将相对于 CSS 文件。
使用 JavaScript 编写属性时,URL 应始终与页面(请求的主要资源)相关。
There is no tildefunctionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
tilde我所知道的 JS 中没有内置功能。通常的方法是定义一个 JavaScript 变量来指定基本路径:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
并在您动态分配 URL 时引用该根。
回答by Vijayanand Settin
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
对于我正在处理的 MVC4 应用程序,我在 _Layout.cshtml 中放置了一个脚本元素,并为所需的路径创建了一个全局变量,如下所示:
<body>
<script>
var templatesPath = "@Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
回答by takepara
I used pekka's pattern. I think yet another pattern.
我使用了 pekka 的模式。我认为还有另一种模式。
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
并在 myjsfile.js 中解析查询字符串。
回答by Mandeep Janjua
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
请使用以下语法在 javascript 中享受 asp.net tilda ("~") 的奢华
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
回答by JamminJamaican
I found this to work for me.
我发现这对我有用。
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
当然在脚本标签之间......(我不确定为什么脚本标签没有出现在这篇文章中)......
回答by gchq
This works well in ASP.NET webforms.
这在 ASP.NET webforms 中运行良好。
Change the script to
将脚本更改为
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
我有每个目录级别的母版页,这是在 Page_Init 事件中
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
现在无论应用程序是在本地运行还是部署,您都会获得正确的完整路径
http://localhost:57387/Images/chevron-large-left-blue.png
回答by Samir Ahmed
You need to add runat="server"and and to assign an ID for it, then specify the absolute path like this:
您需要添加runat="server"和并为其分配一个ID,然后像这样指定绝对路径:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
在代码隐藏中,您可以使用 ID 以编程方式更改 src。

