2012-09-20 18 views
0

我有一個插件可以找到給定父元素中的所有img元素。某些圖像是我需要從陣列中刪除的重複項。我想我可以把他們都到一個數組,然後篩選出重複或而我穿越地圖上做一些有條件的檢查,但不太清楚怎麼做任何如何從jquery對象映射中過濾唯一的data-attr值

JQ插件

(function($){ 
    $.fn.cacheImages = function() { 
    this.find('img').map(function(){ 
     if($(this).attr('data-src') == null ||$(this).attr('data-src') == 'null'){ 
     return; 
     } 
     else{ 
     //do something here if $(this).attr('data-src') has not bed traversed yet 
     } 
    }); 
    }; 
})(jQuery); 

然後叫像

$('#something-with-images').cacheImages(); 

回答

1

,因爲它們使用可以爲您節省的URL到對象?

(function($){ 

    var srcURLs = {}; 

    $.fn.cacheImages = function() { 

     this.find('img').map(function(){ 
      var thisSrc = $(this).attr('data-src'); 

      if(thisSrc == null || thisSrc == 'null' || srcURLs[thisSrc]){ 
       return; 
      } 
      else{ 
       srcURLs[thisSrc] = 1; 
       //do something here if $(this).attr('data-src') has not bed traversed yet 
      } 


    }); 

})(jQuery); 
1

沒有測試,但這應該工作,

(function($){ 
     var list = {}; 
     $.fn.cacheImages = function() { 
     this.find('img').filter(function(){ 
      var src = $(this).data('src'); 
      if(src !== 'null' && src !== null && typeof list[src] == 'undefined') { 
       list[src] = true; 
       return true; 
      } 
      } 
     }); 
     }; 
    })(jQuery); 

.filter()

+1

一個目的查找會比通過整個陣列中的每個時間循環快得多。 – robC

+0

@robC不錯的地方:) – Jashwant

相關問題