如何在ASP.NET项目中正确引用JavaScript文件? [英] How to Properly Reference a JavaScript File in an ASP.NET Project?

查看:103
本文介绍了如何在ASP.NET项目中正确引用JavaScript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些引用javascript文件的页面。

I have some pages that reference javascript files.

应用程序存在于虚拟目录本地,即 http://localhost/MyVirtualDirectory/MyPage.aspx

The application exists locally in a Virtual Directory, i.e. http://localhost/MyVirtualDirectory/MyPage.aspx

所以本地我引用文件如下:

so locally I reference the files as follows:

<script src="/MyVirtualDirectory/Scripts/MyScript.js" type="text/javascript"></script>

但生产设置不同。该应用程序在生产中作为自己的网站存在,因此我不需要包含对虚拟目录的引用。这个问题是我需要修改包含javascript引用的每个文件,如下所示:

The production setup is different though. The application exists as its own web site in production, so I don't need to include the reference to the virtual directory. The problem with this is that I need to modify every file that contains a javascript reference so it looks like the following:

<script src="../Scripts/MyScript.js" type="text/javascript"></script>

我尝试在本地设置中以这种方式引用文件,但它不起作用。

I've tried referencing the files this way in my local setup but it doesn't work.

我是否完全错了?有人可以告诉我我需要做什么吗?

Am I going about this completely wrong? Can somebody tell me what I need to do?

谢谢

推荐答案

以前的答案似乎假设 Scripts 目录始终作为应用程序根目录的子目录存在。如果这个假设是正确的,并且如果页面也在根,那么你的早期标签都可以简单:

Previous answers seem to assume that the Scripts directory always exists as a subdirectory of your application root. If that assumption is correct, and if the page is also at the root, then both of your earlier tags can be simply:

<script src="Scripts/MyScript.js" type="text/javascript"></script>

但我读到的第二个例子是 Scripts 不是总是应用程序根目录的子目录(因为开头的 ../ 会向上移动一个级别,所以脚本将是您的应用程序根目录的对等方。也就是说,你说第二个例子不起作用。 :-)但如果确实如此,我强烈建议调整一个环境或另一个环境以使相对路径一致,然后始终使用上面的相对路径。

But my read of your second example is that Scripts isn't always a subdirectory of your application root (because the ../ at the beginning moves up a level, so Scripts would be a peer of your application root). That said, you did say the second example didn't work. :-) But if that's really the case, I'd strongly recommend adjusting one environment or the other so that the relative paths agree, and then always using relative paths as above.

据我所知,使用 ResolveUrl 的唯一原因是,如果应用程序中的页面位于文件夹结构中,并且标记可能出现在根目录中的页面中或者在子目录中的页面中。如果是这样,你可以在两种情况下都使用 ResolveUrl ,这样你就有了一个锚点。我从不以这种方式创作,我总是确保我知道页面在层次结构中的位置(如果需要有层次结构)并为当前文档使用适当的相对路径。

The only reason for using ResolveUrl as far as I know would be if the pages in the application are in a folder structure and the tag may appear in a page at the root or in a page in a "subdirectory". If so, you can use ResolveUrl in both cases so you have an anchor point. I never author things that way, I always ensure I know where the page will be in the hierarchy (if there needs to be a hierarchy) and use an appropriate relative path for the current document.

这篇关于如何在ASP.NET项目中正确引用JavaScript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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