jquery获取imgsrc并在另一个div中添加为后台
我试图获得一个div中第一个img的图像src,并将其作为背景添加到另一个div中jquery获取imgsrc并在另一个div中添加为后台,jquery,html,Jquery,Html,我试图获得一个div中第一个img的图像src,并将其作为背景添加到另一个div中 <ul class="list-parent"> <li> <!-- add div with background img here --> <div class="img-parent"> <img src="image src origin"> <img src="ignore this image">
<ul class="list-parent">
<li>
<!-- add div with background img here -->
<div class="img-parent">
<img src="image src origin">
<img src="ignore this image">
<img src="ignore this image">
</div>
</li>
<li>
<!-- add div with background img here -->
<div class="image-parent">
<img src="image src origin">
<img src="ignore this image">
<img src="ignore this image">
</div>
</li>
</ul>
-
-
我做了这样的事情:
var rssimg = $('.image-parent img:first-child').attr('src');
$('.img-target li').prepend('<div class="img-target" style="background-image:url(' + rssimg + ')"></div>');
var rssimg=$('.image-parent-img:first-child').attr('src');
$('.img target li')。前置('');
但我只获取first.image父对象的第一个映像的源,而不是直接父对象中每个第一个映像的第一个src
我已经搜索了几个小时,尝试了不同的方法,但到目前为止没有任何效果。我对JQuery几乎是新手,但我很确定有一个解决方案
非常感谢您的专业知识。您需要使用
$.map
和$.get
var rssimg = $('div[class$=parent] img:first-child').map(function(){
return this.src;
}).get();
现在,
rssimg
是一个数组
,它的元素是图像的URL,这些图像是
的后代,这些图像的类
以父级结尾,它们可以通过索引访问。你认为你能举一个如何通过索引访问的例子吗?语法是什么?非常感谢。好的,我想我能弄明白。这就是我所做的:'$.each(rssimg,function(I,val){$('.list parent li').eq(I).prepend('');});'