jQuery:为每个图像添加特定的attr

时间:2011-10-31 10:30:30

标签: jquery attributes

有一个循环(在我的图库脚本中)导致我这样的事情:

        <div class="gallery">
            <a href="uploads/rep2.png">
             <img src="uploads/rep2-150x110.png" class="thumbnail">
            </a>
        </div>
        <div class="gallery">
            <a href="uploads/rep1.png">
             <img src="uploads/rep1-150x110.png" class="thumbnail">
            </a>
        </div>
        <div class="gallery">
            <a href="uploads/rep2.png">
             <img src="uploads/rep2-150x110.png" class="thumbnail">
            </a>
        </div>

我想在此循环中为每个图像添加特定的attr(即每个链接的“href”)。必须是:

        <div class="gallery">
            <a href="uploads/rep2.png">
             <img data-img="uploads/rep2.png" src="uploads/rep2-150x110.png" class="thumbnail">
            </a>
        </div>
        <div class="gallery">
            <a href="uploads/rep1.png">
             <img data-img="uploads/rep1.png" src="uploads/rep1-150x110.png" class="thumbnail">
            </a>
        </div>
        <div class="gallery">
            <a href="uploads/rep2.png">
             <img data-img="uploads/rep2.png" src="uploads/rep2-150x110.png" class="thumbnail">
            </a>
        </div>

我写了这段代码:

$('.thumbnail').each(function() {
var $this = $('.gallery a'),
href = $this.data('href'); 
$('.thumbnail').attr('data-img', href);
        });

但不行。谢谢你的帮助。

5 个答案:

答案 0 :(得分:1)

关闭,但您需要在每次回调中使用this

首先获取图库中的所有标签,找到它们的href,将其应用于作为孩子的img标签。

$('.gallery a').each(function() {
   href = $(this).attr('href');
   $(this).find("img").attr('data-img', href);
});

这里的关键技巧是each()将此变量设置为每次回调迭代的元素。

答案 1 :(得分:0)

试试这个:

$(".gallery").each(function(index, value) {
    $("img", $(value)).attr("data-img", $("a", $(value)).attr("href"));
});

答案 2 :(得分:0)

尝试一下,

$('.thumbnail').each(function(i,n) {
var $this = $(n).parent(),
href = $this.data('href'); 
$('.thumbnail').attr('data-img', href);
});

$('.gallery a') =&gt;这只是获取所有标签,您最终可能会得到相同的href

答案 3 :(得分:0)

Attr可以使用将返回新值的函数:

$('.thumbnail').attr("data-img", function() {
    return this.parentNode.getAttribute("href");
});

答案 4 :(得分:0)

var $this = $('.gallery a');

返回一个数组(所有a元素都带有.gallery)。请尝试以下方法:

$('.gallery img').each(function(){
    $(this).attr('data-img', $(this).parent().attr('href'));
});

这将转到每个img并为其提供一个data-img属性,其值包含a的{​​{1}}。

编辑:正如下面的评论中所指出的,您可能只想要图库中的图片div,因此您应该使用选择器href$('.gallery img')(如果你想跳过非缩略图。)