最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

path - JavaScript load image file from a different directory - Stack Overflow

programmeradmin0浏览0评论

In JavaScript I want to load an image file from a different directory. My file structure is as such:

Project/js/script.js
Project/img/1.png

In script.js I want the following:

document.getElementById("image").src = "Project/img/1.png";

How do I make this work?

In JavaScript I want to load an image file from a different directory. My file structure is as such:

Project/js/script.js
Project/img/1.png

In script.js I want the following:

document.getElementById("image").src = "Project/img/1.png";

How do I make this work?

Share Improve this question asked Nov 10, 2014 at 22:30 Ryan FaulhaberRyan Faulhaber 761 gold badge3 silver badges8 bronze badges 3
  • What is the path of your main HTML file? That is what establishes the base path by which relative paths are evaluated. – jfriend00 Commented Nov 10, 2014 at 22:35
  • Project/index.html – Ryan Faulhaber Commented Nov 10, 2014 at 22:36
  • Try document.getElementById("image").src = "/img/1.png"; – Will Commented Nov 10, 2014 at 22:37
Add a ment  | 

2 Answers 2

Reset to default 1

Your HTML file establishes the base path by which other relative paths are evaluated. So, if your HTML file path is "http://example./something/Project/index.html", then the Project directory is already the default location so you can access other things relative to the Project directory like this:

js/script.js
img/1.png

Any relative path that does not start with a domain or with / will have http://example./something/Project/ prepended to it.

The browser doesn't ever know what root folder the files are in - it only knows what it sees from the URL. It seems like your project's root is in the Project folder, and everything lives under that. (like when you go to http://example./, your web daemon is configured to look in your 'Project' folder?)

so you should be able to do:

document.getElementById("image").src = "/img/1.png";

the first slash says "go to my root folder, whatever that is on the web server", and then the rest is just the remaining path.

发布评论

评论列表(0)

  1. 暂无评论