Using jQuery each to replace image source

时光毁灭记忆、已成空白 提交于 2019-12-08 04:53:05

问题


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>

回答1:


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.




回答2:


$('.image img').each(function(i){
   $('#contentA').find('li:eq('+i+') img').attr('src', $(this).attr('src'));
});


来源:https://stackoverflow.com/questions/5242258/using-jquery-each-to-replace-image-source

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!