Javascript 使用 jquery 更改 img src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6568424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
changing the img src with jquery
提问by gavsiu
The html structure I have is something like:
我拥有的 html 结构类似于:
<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.jpgto file#-896x277.jpg.
我正在尝试将文件名从file#-128x79.jpg 更改为file#-896x277.jpg。
I don't know how to take the dynamically generated filename and search and replace for the src changes.
我不知道如何获取动态生成的文件名并搜索和替换 src 更改。
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.
我找到了用“none”替换整个 src 的方法,以确保到目前为止我做对了,但我不知道如何做其余的。
$('#something').removeAttr('id').prop('class', 'some-class').find('img').prop('src', 'none');
回答by Niklas
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:
您可以通过首先使用选择器选择所有图像,然后使用对内容的回调来替换src
每个img
图像:attr
replace
$('#something img').attr('src',function(i,e){
return e.replace("-128x79.jpg","-896x277.jpg");
})
回答by Muhammad Adeel Zahid
you can assign an id to your image tag like
您可以为您的图像标签分配一个 id,例如
<img id ="pic" src="http://domain.com/directory/file3-128x79.jpg">
then in jquery use
然后在 jquery 中使用
$('#pic').attr('src', 'file#-896x277.jpg');
回答by Roko C. Buljan
回答by Pranay Rana
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
})
});
回答by Alex Pliutau
You should add .children()
before .find('img')
:
您应该在.children()
之前添加.find('img')
:
$('#something').removeAttr('id').attr('class', 'some-class').children().find('img').attr('src', 'none');
回答by Kamyar
回答by hungryMind
$('#something img').attr('src',$('#something img').attr('src').replace(x,y))