简体   繁体   English

如何生成相对于Javascript / jQuery文件的路径?

[英]How can I generate a path relative to a Javascript/jQuery file?

I have a CMS template that uses JavaScript/jQuery to insert an image onto the page. 我有一个CMS模板,该模板使用JavaScript / jQuery将图像插入页面。 This works fine when I specify an explicit path to the image, but because I use the template on several sites, the path needs to be determined automatically. 当我指定图像的显式路径时,这种方法可以很好地工作,但是由于我在多个站点上使用了模板,因此需要自动确定路径。

Making things a little harder is the fact that the path to the template (and therefore the image I'm linking to) changes periodically with each revision to the template. 事情变得有点困难的事实是,模板的每次修订版都会定期更改模板的路径(并因此链接到我的图像)。

Here's the (extremely simple) relevant code at the moment - which technically works in the short term, but is not the solution I'm looking for:- 这是目前(极其简单)的相关代码-从技术上讲短期内有效,但不是我正在寻找的解决方案:-

src = '../template_v1/images/pdf_small.png'

This correctly generates the base URL, but breaks as soon as the template version is incremented (and the path changed) to template_v2 or template_v3 , for example. 例如,这可以正确生成基本URL,但是一旦模板版本增加(并且路径已更改)到template_v2template_v3 ,它就会中断。

The JavaScript/jQuery file (again, included with the template) is located at http://www.domain.com/template_v1/js/this_file.js - so with that in mind, I want to be able to automatically generate a path to the image relative to the location of the this_file.js file. JavaScript / jQuery文件(同样包含在模板中)位于http://www.domain.com/template_v1/js/this_file.js考虑到这一点,我希望能够自动生成路径相对于this_file.js文件位置的图像。 If this were CSS this would be easy, as non-explicit paths are relative to the CSS file calling the path - but I don't know how to accomplish this with JavaScript/jQuery. 如果这是CSS,这将很容易,因为非显式路径是相对于调用该路径的CSS文件而言的-但我不知道如何使用JavaScript / jQuery来实现。

Thanks in advance for any tips. 在此先感谢您提供任何提示。

Do you need to go up a folder at the start of the source? 您是否需要在源代码的开头添加一个文件夹? Would going from the current directory work and stay within the template folder entirely: 从当前目录开始工作,并将其完全保留在template文件夹中:

src = './images/pdf_small.png'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM