我有一个主文件夹“main”。它里面有一个名为“test1.html”的页面。它也有图像文件夹。图像文件夹具有图像“pic1.png”。
在“主”文件夹中还有一个名为“sub”的子文件夹,其中有一个页面“test2.html”。
场景:我在两个页面中(在根文件夹和子文件夹中)通过 jquery 在 img 标签中插入 pic1.png。我应该如何处理不同页面的 src?IE,
test1.html -- 图像/pic1.png
test2.html -- ../images/pic1.png
我有一个主文件夹“main”。它里面有一个名为“test1.html”的页面。它也有图像文件夹。图像文件夹具有图像“pic1.png”。
在“主”文件夹中还有一个名为“sub”的子文件夹,其中有一个页面“test2.html”。
场景:我在两个页面中(在根文件夹和子文件夹中)通过 jquery 在 img 标签中插入 pic1.png。我应该如何处理不同页面的 src?IE,
test1.html -- 图像/pic1.png
test2.html -- ../images/pic1.png
您可以使用正则表达式检查位置并使用 jQuery 中的 attr 函数应用 src
(''+window.location).match(/http:\/\/[^\/]*\/*root\/?(.*)/)[1]
这将在没有第一个斜杠的情况下匹配 root 之后的 url 中的所有内容。
如果它在根目录中,它将为空,您可以..在该变量中应用多少个斜线
var path = (''+window.location).match(/http:\/\/[^\/]*\/*root\/?(.*)/)[1]
if (path) {
var prefix = '';
for (var i=path.match(/\//).length;i--;) {
prefix += '../';
}
$('img').each(function() {
var $this = $(this)
$this.attr('src', prefix + $this.attr('src'));
});
}
这将更改页面上图像的所有 src 属性