问题
I have find related answer but not same like this topic, so i asked this question.
My question is, i'm trying to replace image file name default.jpg
to hqdefault.jpg
from all images below, I'm unable to change image links manually, so i have to change it by jquery.
Images
<div id="selector">
<img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg">
<img src="http://img.youtube.com/vi/ss7EJ-PW2Uk/default.jpg">
<img src="http://img.youtube.com/vi/ktd4_rCHTNI/default.jpg">
<img src="http://img.youtube.com/vi/0GTXMEPDpps/default.jpg">
</div>
JS i'v tried
$('#selector img').attr('src',function(i,e){
return e.replace("default.jpg","hqdefault.jpg");
});
Problem is it change(remove) whole links to hqdefault.jpg
, but i want to change only default.jpg
to hqdefault.jpg
from all/any image src.
How to replace all image file name simply?
Example
<img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg">
to
<img src="http://img.youtube.com/vi/qDc_5zpBj7s/hqdefault.jpg">
Don't use full image link on js, because video generate image links/id dynamically, just replace default.jpg
to hqdefault.jpg
by jquery.
回答1:
try this
$('#selector img').attr('src',function(i,e){
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});
回答2:
You can also try this:
$('#selector img').on({
'click': function(){
var src1 = $(this).attr("src");
var path = src1.substring(0,src1.lastIndexOf('/'));
var new_source=path+'/'+'hqdefault.jpg';
$(this).attr('src',new_source);
}
});
回答3:
You should use each
function to iterate through all img
. Following code snippet may help you.
$('#selector img').each(function(){
var src = $(this).attr('src').replace("default.jpg","hqdefault.jpg");
$(this).attr('src', src);
});
Update:
If you are using LazyLoad XT plugin then do the same in it's onload
event like following.
$.lazyLoadXT.onload=function(){
var src = $(this).attr('src').replace("default.jpg","hqdefault.jpg");
$(this).attr('src', src);
}
来源:https://stackoverflow.com/questions/33971402/replace-image-file-name-by-jquery