使用jQuery分别替换图像源 [英] Using jQuery each to replace image source

查看:116
本文介绍了使用jQuery分别替换图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.在加载时,我想使用每个类来通过".image"类遍历所有div,获取该div中图像的源,并替换相应列表项的源.

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.

以下示例:useThis1将替换item1的源,useThis2将替换item2的源,依此类推.在这方面的任何帮助将不胜感激.

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>

推荐答案

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'));
});

如果要在完全加载DOM时执行该功能,请将功能包装在$(document).ready()中.

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

这篇关于使用jQuery分别替换图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆