【问题标题】:How do I filter unique data-attr values from a jquery object map如何从 jquery 对象映射中过滤唯一的数据属性值
【发布时间】:2012-09-12 19:45:17
【问题描述】:

我有一个插件可以找到给定父元素中的所有 img 元素。一些图像是我需要从数组中删除的重复图像。我想我可以将它们全部放入一个数组中,然后过滤掉重复项,或者在我遍历地图时进行某种条件检查,但不太确定该怎么做

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

【问题讨论】:

    标签: javascript jquery dom jquery-plugins jquery-mobile


    【解决方案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 );
    

    【讨论】:

      【解决方案2】:

      未经测试,但这应该可以工作,

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

      【讨论】:

      • 对象查找比每次循环遍历整个数组要快得多。
      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2017-05-03
      相关资源
      最近更新 更多