问题
The html structure I have is something like:
<ul id="something">
<li>
<a href="">
<img src="http://domain.com/directory/file1-128x79.jpg">
</a>
</li>
<li>
<a href="">
<img src="http://domain.com/directory/file2-128x79.jpg">
</a>
</li>
<li>
<a href="">
<img src="http://domain.com/directory/file3-128x79.jpg">
</a>
</li>
</ul>
I'm trying to change the filename from file#-128x79.jpg to file#-896x277.jpg.
I don't know how to take the dynamically generated filename and search and replace for the src changes.
I found my way to replacing the whole src with 'none' to make sure I got it right so far, but I don't know how to do the rest.
$('#something').removeAttr('id').prop('class', 'some-class').find('img').prop('src', 'none');
回答1:
You can replace the src
for each img
by first selecting all the images with a selector and then using the attr
callback to replace
the contents:
$('#something img').attr('src',function(i,e){
return e.replace("-128x79.jpg","-896x277.jpg");
})
回答2:
you can assign an id to your image tag like
<img id ="pic" src="http://domain.com/directory/file3-128x79.jpg">
then in jquery use
$('#pic').attr('src', 'file#-896x277.jpg');
回答3:
DEMO
$('img').hover(function(){ // or any other method
this.src = this.src.replace("128x79", "200x60");
});
回答4:
You should add .children()
before .find('img')
:
$('#something').removeAttr('id').attr('class', 'some-class').children().find('img').attr('src', 'none');
回答5:
Note : try the following here mouse over is just for the demo purpose only
$(function() {
$("something li a img")
.mouseover(function() {
var src = "over.gif";
$(this).attr("src", src); // change the image source
})
});
回答6:
How about using attr:
this.removeAttr('id').prop('class', 'featured-images').find('img').attr({‘src’:'file#-896x277.jpg’});
回答7:
$('#something img').attr('src',$('#something img').attr('src').replace(x,y))
来源:https://stackoverflow.com/questions/6568424/changing-the-img-src-with-jquery