【问题标题】:Scan DIVs for specific classes to generate unique links扫描特定类的 DIV 以生成唯一链接
【发布时间】:2014-06-16 12:18:50
【问题描述】:

我有一个包含图像/视频/画廊等的 div 列表。 结构如下:

<div class="item image">image content</div>
<div class="item video">video content</div>
<div class="item gallery">gallery content</div>
<div class="item image">image content</div>
<div class="item image">image content</div>
<div class="item video">video content</div>

如您所见,可以有多个具有相同内容类型的 div。 我想要实现的是扫描具有 class=item 的 div 列表并为每种内容类型生成一个按钮。

这是我目前所拥有的,使用 jQuery EACH 函数

$(document).ready(function () {
    $(".item").each(function () {
        if ($(this).hasClass("image")) {
            alert('image found');
        };
        if ($(this).hasClass("video")) {
            alert('video found');
        };
    });
});

问题是警报被多次执行,每个 div 的类等于我的条件。由于我计划为每种内容类型生成按钮,因此当前代码将添加重复按钮,因为多个 div 可以拥有一类视频/图像。

我尝试在 IF 条件中使用“return false”,但这会破坏我的整个 EACH 函数,在第一次引用时停止。

【问题讨论】:

  • 你的按钮生成代码在哪里..?
  • 为您设置为 false 的每个内容类型添加一个变量?
  • 我还没有那个代码,因为这个EACH函数有优先权,那我改一下题目吧。
  • 可以有几种类型?
  • 最多可以有10种内容类型:音频、视频、报价、链接、图片、图库、状态、聊天

标签: javascript jquery html


【解决方案1】:

您可以创建一个临时变量来跟踪您已经遍历了哪些项目类型

(function() {
    var types = {},
    type_re = /\b(?:audio|video|quote|link|image|gallery|status|chat)\b/g;

    $('.item').each(function() {
        var m = this.className.match(type_re);

        if (m !== null && !types.hasOwnProperty(m[0])) {
            // code to add button
            console.log('add button for type ' + m[0]);

            types[m[0]] = true;
        }
    });
}());

Demo

以前的答案

您可以先创建一个数组,该数组将包含文档中找到的所有类型:

var types = [],
type_re = /audio|video|quote|link|image|gallery|status|chat/g;

$('.item').each(function() {
    var m;

    while ((m = type_re.exec(this.className)) !== null) {
        if (!$.inArray(types, t[0])) {
            types.push(t[0]);
        }
    }
});

// types is an array with all types found

或者,遍历所有可能的类型并根据每种类型过滤项目:

var $items = $('.item'),
types = ['audio', 'video', 'quote', 'link', 'image', 'gallery', 'status', 'chat'];

$.each(types, function(_, type) {
    var $itemsOfType = $items.filter(function() {
        return (' ' + this.className + ' ').indexOf(type) != -1;
    });
    if ($itemsOfType.length) {
    }
});

【讨论】:

  • 感谢 Jack,您的解决方案也可以开箱即用(如 Alex'es)。在我选择最佳答案之前,您认为哪个更有效?
  • 连接到 jsperf 并检查性能;我真的不能说,因为我不知道文档大小等。
【解决方案2】:

一些非常简单的方法是为每个可能的内容类型添加一个状态变量并检查它:

$( document ).ready(function() {        
    var _image = true,
        _video = true;
    $( ".item" ).each(function() {

      if ($(this).hasClass( "image" ) && _image) {
        _image = false;
        alert('image found');
      };
      if ($(this).hasClass( "video" ) && _video) {
        _video = false;
        alert('video found');
      };

    });
}); 

【讨论】:

  • 感谢 Alex,您的解决方案开箱即用,现在我只收到一次警报,对于每个帖子类型 (div),即使页面上显示了多个。这段代码效率高吗?
  • 是的。如果由于性能,该长度的语句并不重要
  • 如果您将 _image 作为检查的第一个条件会更快,如下所示:if (_image &amp;&amp; $(this).has...)
  • 希望我能选择两个最佳答案,但我不得不使用 Jack 的代码,因为它要短得多,而且开箱即用。非常感谢!
  • 我不是为了声望,但我很确定测试布尔值比读/写数组更有效。但是千斤顶的做法看起来更专业。正如我所说,我的方法很简单
【解决方案3】:

你可以这样做。

if($(".image").length>0)
  {
      alert("image Found")
      //generate button
  }

【讨论】:

    【解决方案4】:

    JSFIDDLE http://jsfiddle.net/rWrCA/

    您可以轻松地使用一个数组来表示类型,并使用另一个数组来判断这些类型是否存在。看起来像:

    $(document).ready(function () {
        // a list of all types and a list of types that were found
        var allTypes = ["image", "video", "gallery"];
        var typesFound = [];
    
        // loop over all items and add types to the list of found types
        $(".item").each(function () {
            for (var idx = 0; idx < allTypes.length; idx++) {
              if ($(this).hasClass(allTypes[idx])) {
                if (typesFound.indexOf(allTypes[idx]) < 0) {
                  typesFound.push(allTypes[idx]);
                }
              }
            }
        });
    
        // as in the original code - prove this worked by displaying alerts!
        for (var idx = 0; idx < typesFound.length; idx++) {
          alert(typesFound[idx] + ' found');
        }
    });
    

    我认为应该这样做!

    【讨论】:

      【解决方案5】:

      在您的 jQuery 就绪函数中创建一个对象。完成循环后,使用按钮对象编写按钮。

      $(document).ready(function () {
          var buttons = {};
          $(".item").each(function () {
              if ($(this).hasClass("image")) {
                  buttons.image = 1;
              };
              if ($(this).hasClass("video")) {
                  buttons.video = 1;
              };
          });
          // write buttons
          for (var type in buttons) {
            $('<button/>', {
              text: type,
              id: 'btn_'+ type,
              click: function () { alert('hi'); }
            }).appendTo('body');
          }
      })
      

      【讨论】:

        猜你喜欢
        • 2014-01-19
        • 2017-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        相关资源
        最近更新 更多