简体   繁体   中英

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. 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.

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. 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.

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:

src = './images/pdf_small.png'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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