【问题标题】:Filter elements that have matching data-filter and class name using jQuery使用 jQuery 过滤具有匹配数据过滤器和类名的元素
【发布时间】:2018-02-04 21:28:39
【问题描述】:

我有一个带有数据过滤器的按钮 div。

<div class="filters">
  <button class="selected" data-filter="all">Show All</button>
  <button data-filter="type-one">Show One</button>
  <button data-filter="type-two">Show Two</button>
  <button data-filter="type-three">Show Three</button>
</div>

单击按钮应将类 .match 添加到列表的特定 li 元素,该元素与单击按钮的数据过滤器具有相同的类名。

<ul class="elements">
  <li class="type-one other-class">Element 1</li>
  <li class="type-two other-class">Element 2</li>
  <li class="type-three other-class">Element 3</li>
</ul>

被点击的按钮也应该只对他应用 .selected。

Here is a Fiddle link

我无法成功比较两个不同元素的数据过滤器和类名,并且只向一个 li 而不是全部添加一个类。可能遗漏了一些非常明显的东西。另外,我已经省略了我的 JS 代码,以换取新的看法。

欢迎任何帮助。

【问题讨论】:

  • 没有 js 代码(你故意遗漏了),我们直到现在才看到你尝试了什么。
  • 请添加您目前尝试过的内容。

标签: javascript jquery


【解决方案1】:

你可以试试下面的

//this event handler will listen to buttons click
$("button").click(function(){
  //remove selected class from all buttons
  $("button").removeClass("selected");

  //add selected class only to clicked button
  $(this).addClass("selected");

  //get data type filter
  var dataFilter = $(this).data('filter');

  //if data filter is all show all of them
  if(dataFilter == "all") {
      $(".elements li").show();
  }
  else
  {
    //else hide all of them and show only the one with correct data filter
    $(".elements li").hide();
    $("." + dataFilter).show();
  }
});

【讨论】:

  • 感谢您的时间和 cmets,那 .是问题:)
【解决方案2】:

农民的方式:

$('button').click(function(){
    $('button').removeClass('selected');
  $('li').removeClass('selected');
  if($(this).attr('data-filter') == 'all') {
    $('li').addClass('selected');
  } else {
    $('.'+$(this).attr('data-filter')).addClass('selected');
    $(this).addClass('selected');
  }
});

JSFiddle : https://jsfiddle.net/ggdv613j/3/

【讨论】:

  • 这有点接近,但如果 li 的类等于按钮的 att(数据过滤器),则 li 应该具有 .match 类。 .match CSS 可以是 .match {background: blue;}
  • 抱歉,我没有真正阅读要求,因为您没有发布任何您尝试过的代码。这只是一个 30 秒的农民回答:D
  • 感谢您的努力,我现在知道了。我已经忽略了 JS,因为我在这方面花了很长时间很尴尬
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 2012-01-04
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多