简体   繁体   English

如何使用jQuery更改图像src

[英]How to change image src using jQuery

<div class="branding">
<h1 class="logo">
<a href="http://www.whatever.com/" class="logo">
<img src="http://www.whatever.com/test.png"></a>
</h1>
</div>

I am trying to access the image src with the following to no avail: 我正在尝试访问图像src而无济于事:

$("a.logo img").html("<img src='http://www.whatever.com/newimage.png'>");

The reason I am doing this is because the image is on a third party that I can't access the codebase to make the change so I am trying to rip out their with my code. 我这样做的原因是因为该图像位于第三方上,因此我无法访问代码库进行更改,因此我尝试将其与我的代码分开。

src is attribute. src是属性。 You should use .attr() to get/set attribute values using jquery: 您应该使用.attr()通过jquery获取/设置属性值:

 $("a.logo img").attr("src","http://www.whatever.com/newimage.png");

.html() changes the html CONTENT of a node, eg .html()更改节点的html内容,例如

orig: <p>foo</p>
$('p').html('bar');
neW: <p>bar</p>

An <img> has NO content. <img>没有内容。 Try 尝试

$('p.logo img').attr('src', 'new url here');

你试过了吗

img.attr('src','http://mynewsource.com');

I figured out the answer: 我想出了答案:

$('a.logo img').attr("src", "http://www.whatever.com/newimage.png" );

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM