这是一个有点绕圈子,但很干净的:
// 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);
});
它可能会在循环遍历唯一值时应用该类,但这更清楚,因为它确保计数正确并且更有趣,因为它使用两个不同的 jqueryeach()
函数。
小提琴进行测试。