简体   繁体   English

用jQuery做这个简单过滤器的更好方法是什么

[英]What is a better way to do this simple filter with jQuery

I am learning jQuery I made a simple selection filter with a basic knowledge with the purpose of learning new techniques. 我正在学习jQuery我做了一个简单的选择过滤器,其基本知识是为了学习新技术。 My question is, what is a better maybe more complex way to do this: https://codepen.io/frivolta/pen/LLwjjy 我的问题是,有什么更好的可能更复杂的方法: https//codepen.io/frivolta/pen/LLwjjy

$(".elementFilter li").on("click",eventTrigger);

function eventTrigger(){
  var getFilterName = $(this).attr("class");
  if(getFilterName!="all"){
  $(".elementList li:not([data-category='"+getFilterName+"'])").hide(); 
  $(".elementList [data-category='"+getFilterName+"']").show();
  }else{
     $(".elementList li").show();
  }
}


<div class="elements">
  <ul class="elementFilter">
    <li class="all">Show all</li>
    <li class="filterOne">Filter One</li>
    <li class="filterTwo">Filter Two</li>
    <li class="filterThree">Filter Three</li>
    <li class="filterFour">Filter Four</li>
  </ul>
  <ul class="elementList">

    <li data-category="filterOne">Filter One</li>
    <li data-category="filterTwo">Filter Two</li>
    <li data-category="filterThree">Filter Three</li>
    <li data-category="filterFour">Filter Four</li>
  </ul>
</div>

I'd like to separate functions and passing parameters between them, if you have any advice I would be glad to hear that. 我想在它们之间分离函数和传递参数,如果你有任何建议我会很高兴听到。 Thanks, F. 谢谢,F。

Your code is almost fine but it will not run if you change add some other class in li elements. 你的代码几乎没问题,但如果你改变在li元素中添加一些其他类,它将无法运行。 See my code below. 请参阅下面的代码。 I showed the problem with the solution. 我向解决方案展示了问题。

$(".elementFilter li").on("click",eventTrigger);

function eventTrigger(){
  var isClasssAll = $(this).hasClass("all");
  var getFilterName = $(this).attr("data-category");

  if(!isClasssAll){
  $(".elementList li:not([data-category='"+getFilterName+"'])").hide(); 
  $(".elementList [data-category='"+getFilterName+"']").show();
  }else{
     $(".elementList li").show();
  }
}



<div class="elements">
  <ul class="elementFilter">
    <li class="all asdasd">Show all</li>
    <li data-category="filterOne" class="filterOne 1">Filter One</li>
    <li data-category="filterTwo" class="filterTwo 2">Filter Two</li>
    <li data-category="filterThree" class="filterThree 3">Filter Three</li>
    <li data-category="filterFour" class="filterFour 4">Filter Four</li>
  </ul>
  <ul class="elementList">

    <li data-category="filterOne">Filter One</li>
    <li data-category="filterTwo">Filter Two</li>
    <li data-category="filterThree">Filter Three</li>
    <li data-category="filterFour">Filter Four</li>
  </ul>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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