我的网站结构如下:
root --> such as localhost or example.com or file:///... etc.
|--css
|--image
: |--folder --> root/image/folder/
|--js
: |--script.js --> root/js/script.js
|--page
: |--index.html --> root/page/index.html
|--index.html --> root/index.html
我使用 jQuery 为 root/index.html
编写图像并保存到 root/js/script.js
var db = {
"images" : [
{"image-url": "image/folder/myImage.png"},
{"image-url": "image/folder/myImage.png"},
{"image-url": "image/folder/myImage.png"}
]
}
$.each(db.images, function (key, data) {
var image = data['image-url'];
$('body').append('<image src="' + image + '" />');
}
它工作正常。我的图像正在显示。我将尝试在 root/page
中创建 index.html
并在此页面上使用 ../js/script.js
。
但它似乎没有显示任何图像。在浏览器上显示图像的空白框。我将尝试查看 F12 并发现 image-url
返回此值。
GET root/page/image/folder/myImage.png net::ERR_FILE_NOT_FOUND
但我想在 root/image/folder/myImage.png
引用我的图像。我不知道如何编写引用图像 url 的脚本来编写图像并在使用相同脚本的任何页面上显示。不能有人来解决这个问题。
在此先感谢并为我的技能感到抱歉。
最佳答案
- 如果您有多个静态图片,那么使用 CSS 会更好:
如果您的 CSS 文件中有 background-image
定义,那么它适用于任何相对路径。
CSS(root/css/site.css
):
.some-image {
background-image: url('../image/your-image.png`);
}
现在,如果您将它包含在 root/index.htm
和 root/page/index.htm
中,它将对它们都有效。
如果您的图片是动态的并且由 PHP 或其他任何工具生成,您可以使用以下 URL:
var db = { "images" : [ {"image-url": "/image/folder/myImage.png"}, {"image-url": "/image/folder/myImage.png"}, {"image-url": "/image/folder/myImage.png"} ] };
URL 中有一个前导斜杠。即,结果如下:
<img src="/image/folder/myImage.png"/>
它是一个绝对路径引用。 URL 将从域的根计算。
例如,对于 http://localhost
它将是 http://localhost/image/folder/myImage.png
,并且它对于任何页面都是相同的你的主人。
请注意,
- 如果您的站点位于子文件夹中,绝对 URL 仍将指向根文件夹
- 对于 file
协议(protocol),/
将指向驱动器的根目录
您可以使用 BASE
标记来指定您的基本 URL。
在 this Stackoverflow topic 阅读更多相关信息和 this Webmasters Stackexchange topic .
关于javascript - 如何为引用图像 url 编写 javascript,以便在使用相同脚本的任何页面上编写图像和显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32774686/