选择具有相同来源的图像,为每个图像添加唯一的类

时间:2013-09-15 20:50:46

标签: jquery

我想将相同的类添加到源相同的图像中。例如,我有这个

<img src="abc.png">
<img src="abc.png">
<img src="def.png">
<img src="def.png">
<img src="ghi.png">

我想跟随

<img src="abc.png" class="g1">
<img src="abc.png" class="g1">
<img src="def.png" class="g2">
<img src="def.png" class="g2">
<img src="ghi.png" class="g3">

3 个答案:

答案 0 :(得分:0)

如果您知道要查找的来源,可以使用属性选择器:

$("img[src='abc.png']").each(function () {
    $(this).addClass("g1");
});

$("img[src='def.png']").each(function () {
    $(this).addClass("g2");
});

$("img[src='ghi.png']").each(function () {
    $(this).addClass("g3");
});

如果你的来源是动态的,试试这个:

var items=new Object();
var idx = 0;
$("img").each(function () {

    var src = $(this).attr("src");
    var newClass = "";
    if (items[src])
        newClass = items[src];
    else {
        idx++;
        newClass = "g" + idx;
        items[src] = newClass;
    }

    $(this).addClass(newClass);

});

小提琴:http://jsfiddle.net/xX83X/

答案 1 :(得分:0)

换句话说,尝试这样的事情:

$(document).ready(function () {

    var images = $("img") , number = 0 , imgLastSrc = null;
    images.each(function(){
        var imgSrc = $(this).attr("src");
        if(imgSrc != imgLastSrc){         
            imgLastSrc = imgSrc;
            number++;
        }
        $(this).addClass("g" + number);
    });

});

参见 JsFiddle

答案 2 :(得分:0)

这是一个有点圆,但干净的:

//  get jquery object of img elements
var allImages = $('img[src]');

// filter out duplicates
allImages = $.unique(allImages);

// instantiate empty array to hold src attr values
var imageSrcs = [];


// loop through elements and push unique src values to imageSrcs   
allImages.each(function() {
  if ( $.inArray( $(this).attr('src'), imageSrcs ) == -1) {
    imageSrcs.push($(this).attr('src'));
  }
});

// loop through unique src attributes array and use in selector to apply .addClass     
$.each(imageSrcs, function(index, value) {
    $("img[src='" + value + "']").addClass("g" + index);
});

它可能会应用该类,因为它循环遍历唯一值,但这更加清晰,因为它确保计数正确并且更有趣,因为它使用两个不同的jquery each()函数。

Fiddle for testing.