使用 jquery 更改 img src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15414462/
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
change img src using jquery
提问by Athapali
<div class="s4-titlelogo">
<a href="/sites/mysite">
<img name="onetidHeadbnnr0" id="ctl00_onetidHeadbnnr2" style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px;" alt="bobpub" src="/_layouts/images/blank.gif" complete="complete"/>
</a>
</div>
If the src attribute of the img is blank.gif, then i want to set the src attribute to my icon url "/_layouts/images/myicon.gif". I need to reference the img as this $('.s4-titlelogo img').
如果 img 的 src 属性是 blank.gif,那么我想将 src 属性设置为我的图标 url "/_layouts/images/myicon.gif"。我需要将 img 引用为 $('.s4-titlelogo img')。
SO FAR:
迄今为止:
iconurl = $('.s4-titlelogo a>img').attr("src");
if (iconurl == ""/_layouts/images/blank.gif")
{
}
回答by James Donnelly
If the src attribute of the img is blank.gif...
如果img的src属性为blank.gif...
if($('.s4-titlelogo img').attr('src') === '/_layouts/images/blank.gif')
...then i want to set the src attribute to my icon url.
...然后我想将 src 属性设置为我的图标 url。
$('.s4-titlelogo img').attr('src', '/_layouts/images/myicon.gif');
Edit: Three downvotes instantly? Uh... why?
编辑:立即投三票?呃……为什么?
Here's a JSFiddleexample to prove that this works.
这是一个JSFiddle示例来证明这是有效的。
回答by Oscar Jara
Just do this...
就这样做...
Live demo:http://jsfiddle.net/oscarj24/FW4kj/
现场演示:http : //jsfiddle.net/oscarj24/FW4kj/
$(function(){
//Get the element
elem = $('.s4-titlelogo img');
//If 'src' attribute contains 'blank.gif'
if (elem.prop('src').indexOf('blank.gif') > 0)
//Replace 'src' attribute with 'myicon.gif'
elem.prop('src', '/_layouts/images/myicon.gif');
//Alert new 'src' attribute just to verify
alert('New image url is: ' + elem.prop('src'));
});