Using jQuery each to replace image source

2019-06-01 06:37发布

I have the following issue. On load I want to use each to go through all the divs with the ".image" class, get the source of the image in that div and replace the source of the corresponding list item.

Example below: useThis1 will replace the source of item1, useThis2 will replace the source of item2, so on and so forth. Any help on this would be much appreciated.

<div class="image"><img src="useThis1"/></div>
<div class="image"><img src="useThis2"/></div>
<div class="image"><img src="useThis3"/></div>
<div class="image"><img src="useThis4"/></div>
<div class="image"><img src="useThis5"/></div>

<div id="contentA">
<ul>
<li><img id="item1" src="toReplaceThis"></li>
<li><img id="item2" src="toReplaceThis"></li>
<li><img id="item3" src="toReplaceThis"></li>
<li><img id="item4" src="toReplaceThis"></li>
<li><img id="item5" src="toReplaceThis"></li>
</ul>
</div>

2条回答
2楼-- · 2019-06-01 06:54
$('.image img').each(function(i){
   $('#contentA').find('li:eq('+i+') img').attr('src', $(this).attr('src'));
});
查看更多
孤傲高冷的网名
3楼-- · 2019-06-01 06:57
var dvImages = $('.image img');  //array of usethis images
var liImages = $('#contentA img'); //array of item images

$.each(dvImages, function(index){
    if(index == liImages.length)
        return false;
    $(liImages[index]).attr('src', $(this).attr('src'));
});

Wrap the function in $(document).ready() if you want it to execute when the DOM is fully loaded.

查看更多
登录 后发表回答