2016-10-08 72 views
-1

我想找到一种方法来选择在div中找到的第一个图像并替换图像源。它特别必须是这种方法,因为图像没有ID(复杂解释)。在div中选择第一个图像并替换图像src

$('.promo-unit-site-logo-3').find('img:first').attr'('src', 'blank')')'; 

我已经尝试使用上面的代码从谷歌搜索和裁剪的东西在一起,但我通过JavaScript的方式新手。

任何帮助表示赞赏!

感谢, 约翰

+0

用'attr'功能之外引号是什么,是只是一个错字? – adeneo

+0

'$('。promo-unit-site-logo-3')。find('img:first')。attr('src','blank');' – adeneo

回答

0

看到它的工作。你在代码中犯错。

var image = $('.promo-unit-site-logo-3').find('img:first').attr('src', 'blank'); 
 
console.log(image.attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="promo-unit-site-logo-3"> 
 
    <img src="http://placehold.it/280x210" title="first image"> 
 
    <img src="http://placehold.it/30x20" title="Second image"> 
 
</div>

+0

辉煌的代码很棒。我现在唯一的问题是它在DOM reaady上这样做。无论如何,我可以预装图像加载,取而代之? 基本上,我们有一个非常限制性的电子商务平台,无法访问CMS配置。 使用您的代码我可以替换我们网站上需要的图片。因为它已经准备好了,它当然会显示图像然后取代它。 –