包含的 Javascript 页面的路径 [英] Path to included Javascript page

查看:24
本文介绍了包含的 Javascript 页面的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取包含的 javascript 文件的绝对路径或站点相对路径.

How do I get the absolute or site-relative path for an included javascript file.

我知道这可以在 PHP 中完成,(__file__,我认为).即使对于包含的页面,也可以检查路径(到包含的文件).有没有办法在 Javascript 中实现这种自我意识?

I know this can be done in PHP, (__file__, I think). Even for an included page, one can check the path (to the included file). Is there any way to have this self awareness in Javascript?

我知道我可以获取页面 URL,但需要获取 JS URL.

I know I can can get the page URL, but need to get the JS URL.

例如.Javascript 需要修改页面上图像的 src.我知道图像相对于 JavaScript 文件的位置.我不知道 Javascript 相对于页面的位置.

Eg. Javascript needs to modify the src of an image on the page. I know where the image is relative to the JavaScript file. I don't know where the Javascript is relative to the page.

<body>
  <img id="img0" src="">
  <script src="js/imgMaker/myscript.js"></script>
</body>

function fixPath(){ 
  $$("#img0")[0].set('src','js/imgMaker/images/main.jpg');
}

请不要告诉我重构我的函数 - 示例已简化以解释需求.在实际案例中,正在分发一个 Mootools 类,人们可以将其放入任何他们想要的文件夹中.

Please do not tell me to restructure my function - the example is simplified to explain the need. In the actual case, a Mootools class is being distributed and people can put it into whatever folder they want.

我只想读取脚本元素的 src,但该类可以是任意数量的 javascript 文件的一部分,所以我不知道该元素是什么样子.

I would just read the src of the script element, but the class can be part of any number of javascript files, so I can't know what the element looks like.

推荐答案

JavaScript(不是 JScript)没有文件名的概念.它是为 Netscape 开发的.因此,没有 __file__ 功能或任何类似功能.

JavaScript (not JScript) has no concept of file names. It was developed for Netscape back in the days. Therefore there is no __file__ feature or anything similar.

最接近的是这两种可能性:

The closest you can come are these two possibilities:

  1. 你已经提到的:收集所有 JS 文件的所有 src 属性并尝试找出哪个是正确的.

  1. What you already mentioned: Harvest all src attributes of all JS files and try to figure out which one is the right.

使它成为一个必要选项,必须在嵌入的 HTML 文件中设置图像的路径.如果未设置,请使用合理且有据可查的默认值:

Make it a necessary option, that the path to the images must be set in the embedding HTML file. If not set, use a reasonable and well-documented default:

<小时>

<script type="text/javascript">
var options = {
  'path_to_images': '/static/images/' // defaults to '/js/img/'
};
</script>

这篇关于包含的 Javascript 页面的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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