I have an image tag..
我有一个图片标签..
<img src="/folder1/folder2/image.jpg">
I need to, using javascript / query remove the first forward slash from the src tag to make the image tag like this.
我需要,使用javascript / query从src标签中删除第一个正斜杠,使图像标签像这样。
<img src="folder1/folder2/image.jpg">
I would like to do this for any image on the page.
我想对页面上的任何图像执行此操作。
Any thoughts?
有什么想法吗?
Justin
贾斯汀
1 个解决方案
#1
11
Tested and works:
经过测试和工作:
$('img').each(
function(){
var src = $(this).attr('src');
if (src.indexOf('/') === 0){
this.src = src.replace('/','');
}
});
JS小提琴演示。
As per nnnnn's suggestion, in comments below, an alternative solution using substring()
:
根据nnnnn的建议,在下面的评论中,使用substring()的替代解决方案:
$('img').each(
function(){
var src = $(this).attr('src');
if (src.indexOf('/') === 0){
this.src = src.substring(1);
}
});
JS小提琴演示。
Note that I'm using:
请注意,我正在使用:
var src = $(this).attr('src');
because I want the actual contents of the attribute, rather than the browser's evaluated interpretation of that attribute (for example with src="/folder1/folder2/image.jpg"
on jsFiddle this.src
returns http://fiddle.jshell.net/folder1/folder2/image.jpg
).
因为我想要属性的实际内容,而不是浏览器对该属性的评估解释(例如在jsFiddle上使用src =“/ folder1 / folder2 / image.jpg”this.src返回http://fiddle.jshell.net /folder1/folder2/image.jpg)。
#1
11
Tested and works:
经过测试和工作:
$('img').each(
function(){
var src = $(this).attr('src');
if (src.indexOf('/') === 0){
this.src = src.replace('/','');
}
});
JS小提琴演示。
As per nnnnn's suggestion, in comments below, an alternative solution using substring()
:
根据nnnnn的建议,在下面的评论中,使用substring()的替代解决方案:
$('img').each(
function(){
var src = $(this).attr('src');
if (src.indexOf('/') === 0){
this.src = src.substring(1);
}
});
JS小提琴演示。
Note that I'm using:
请注意,我正在使用:
var src = $(this).attr('src');
because I want the actual contents of the attribute, rather than the browser's evaluated interpretation of that attribute (for example with src="/folder1/folder2/image.jpg"
on jsFiddle this.src
returns http://fiddle.jshell.net/folder1/folder2/image.jpg
).
因为我想要属性的实际内容,而不是浏览器对该属性的评估解释(例如在jsFiddle上使用src =“/ folder1 / folder2 / image.jpg”this.src返回http://fiddle.jshell.net /folder1/folder2/image.jpg)。