jQuery均未提取具有所选类名的所有元素

时间:2019-04-08 15:45:02

标签: javascript jquery bootstrap-4

我有一个带有搜索框和5张Boostrap卡的页面。我这样做的目的是,如果您在框中搜索并且文本与data-tags属性中的文本不匹配,则卡片应该隐藏起来。它可以正常工作,但不拉卡。它只会将卡拉到第一个card-deck容器下面。它会忽略第二张卡片下的所有卡片。我故意将data-tags属性设置为“ nothing”,然后尝试搜索:

enter image description here

enter image description here

我做了一个JS小提琴:https://jsfiddle.net/perezdev/krdgmuf4/7/

如果您搜索“ isol”,则只有第一张卡片出现,因为该短语与属性匹配:

enter image description here

这是JS / Jquery的核心:

$(".card").each(function () {
    var tags = $(this).attr('data-tags');

    if (tags !== undefined && tags !== null) {
      var matchIndex = tags.indexOf(text);
      if (matchIndex > -1) {
        $(this).show();
      }
      else {
        $(this).hide();
      }
    }
  });

对我在这里做错的任何想法吗?

1 个答案:

答案 0 :(得分:1)

也许尝试将data-tags放在card元素上而不是card-deck元素上。当前代码从card读取此属性:

$(".card").each(function () {
    var tags = $(this).attr('data-tags');