jquery - 通过 2 个选择列表过滤 html 表格

标签 jquery filtering

我想通过 2 个选择列表过滤(隐藏除选择之外的所有条目)表行中的多个条目。 第一个包含国家,第二个包含年份。

我可以编写一个按单个参数进行过滤的脚本,但是当用户选择德国和 2017 年时如何扩展功能(显示 2017 年德国的所有项目)?

<select class="form-control" id="filter-by-country">
  <option selected="selected">COUNTRY</option>
  <option>ALL</option>
  <option>Belgium</option>
  <option>Germany</option>
  <option>Russia</option>
</select>

<select class="form-control" id="filter-by-year">
  <option selected="selected">COUNTRY</option>
  <option>ALL</option>
  <option>2018</option>
  <option>2017</option>
  <option>2016</option>
  <option>2015</option>
</select>

<table class="table table-hover all-projects">
  <thead>
    <tr>
      <th scope="col">order date</th>
      <th scope="col">project id</th>
      <th scope="col">full project's name</th>
      <th scope="col">quantity</th>
      <th scope="col">order no</th>
    </tr>
  </thead>
  <tbody>
    <tr class="text-center belgium 2018">
      <td>27.09.2018</td>
      <td></td>
      <td class="text-left">First project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class="text-center germany 2017">
      <td>27.09.2017</td>
      <td>5461</td>
      <td class="text-left">Second project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class="text-center russia 2016">
      <td>27.09.2016</td>
      <td>5462</td>
      <td class="text-left">Third project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class="text-center russia 2018">
      <td>27.09.2018</td>
      <td>5462</td>
      <td class="text-left">Fourth project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tbody>
</table>

最佳答案

应该可以做到(一条建议:CSS类名不能以数字开头,这是非法的,按选择项值过滤,而不是文本)

var filter_c=$('#filter-by-country');
var filter_y=$('#filter-by-year');
$('.filter_control').on('change', function(e){

var class_c=filter_c.val().toLowerCase();
var class_y='y'+filter_y.val().toLowerCase();
$('.all-projects tr.text-center').hide();
if(class_c=='country' || class_c=='all' ){
class_c='text-center'
}
if(class_y=='yyear' || class_y=='yall' ){
class_y='text-center'
}
console.log('.'+class_c+' .'+class_y)
$('.'+class_c+'.'+class_y).show();
});

代码笔:https://codepen.io/peker-ercan/pen/jeqpQx

关于jquery - 通过 2 个选择列表过滤 html 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52645094/

相关文章:

mysql - 查询 SQL 的 4 个字段(共 5 个)不同,返回表中的所有字段

优化逻辑以从列表中过滤/提取数据的pythonic方法

c++ - opencv:如何在方向图像上绘制箭头

javascript - Charts.js donut

javascript - .each(function() 中包含多个函数 - jQuery

javascript - 如何将特定列表元素传递给 Javascript 函数

python - Django 中过滤内的正则表达式

javascript - Jquery 选择以 ID 为条件的表单项

javascript - setinterval 说没有定义函数,但它是

php - 获取两个二维数组的关联行之间的差异