Filtering duplicate img src with jQuery unique or remove

北慕城南 提交于 2019-12-20 02:06:39

问题


I've tried different workarounds that have been discussed here, but none of them are working in my case.

This is my source:

<div class="colourDots">
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.sw.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>
   <img src="/out/pictures/generated/product/8/300_450_100/60028.bl.jpg"/><br>

I would like to show only unique "img src" of the above list, no duplicated pictures ...

Script:

var uniqueImg = $(".colourDots img").get();
divs = $.unique(uniqueImg);

I'm getting the same source again :-(

Any ideas or any other workarounds?


回答1:


Try this:

$(function(){
    var srcs = [],
        temp;
    $(".colourDots img").filter(function(){
        temp = $(this).attr("src");
        if($.inArray(temp, srcs) < 0){
            srcs.push(temp);   
            return false;
        }
        return true;
    }).remove();
});

Here is the link http://jsfiddle.net/xCjjp/




回答2:


what i'll do is, first get all those image tag's src attr into an array

var img_array = $(".colourDots img").map(function() {
  return $(this).attr("src");
});

Now here i can do duplicate check process within this array and remove all the img whose src is found more than once in this array, here all img are removed so i'll add back one single image of src.




回答3:


you could use:

$(".colourDots img").​​​​​​​​each(function(){
    if($(this).parent().length)
        $(".colourDots img:contains('" + $(this).jpg() + "')").not(this).remove();
});​

See http://www.jquery4u.com/jquery-functions/jquery-each-examples/




回答4:


Here is another version I put together from all answers:

var img_array = $(".colourDots img").map(function() {
  return $(this).attr("src");
});
img_array = $.unique(img_array);
img_array.each(function(index, value){
    var sel = '.colourDots img[src="' + value+ '"]';
    $(sel).not($(sel + ':first')).remove();
});

http://jsfiddle.net/GZWY5/3/



来源:https://stackoverflow.com/questions/8415910/filtering-duplicate-img-src-with-jquery-unique-or-remove

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