我有一个主文件夹“main”。它的页面里面有名称“test1.html”。它还有images文件夹。 图像文件夹的图像为“pic1.png”。
“main”文件夹中还有一个名为“sub”的子文件夹,其中有一个页面“test2.html”。
SCENARIO :我在两个页面(根文件夹和子文件夹)中通过jquery在img标签中插入pic1.png。我该如何处理不同页面的src?即,
test1.html - images / pic1.png
test2.html - ../ images / pic1.png
答案 0 :(得分:3)
答案 1 :(得分:0)
您可以使用正则表达式检查位置,并使用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属性