简体   繁体   中英

How do I filter unique data-attr values from a jquery object map

I have a plugin that finds all img elements within a given parent element. Some of the images are duplicates that I need to remove from the array. I'm thinking I can put them all into an array and then filter the duplicates out or while i'm traversing the map do some sort of conditional check but not quite sure how to do either

jq plugin

(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 );

then called like

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

You could save the URLs to an object as they are used?

(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 );

Not tested, but this should work,

 (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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM