javascript - 如何使用select dropdown过滤表td值

标签 javascript jquery html css

我有一个表,其 td 值对应于选择下拉列表的值。 So when the dropdown is being selected, i would like the table to filter its table row according to the selected value.例如,如果选择了一个, 该表将进行过滤,只显示 td 值为 1 的两个表行。目前,由于某种原因,该代码无法正常工作。

$(document).ready(function($) {
 
  $('#select').change(function() {
   
    var selection = $(this).val();
    var dataset = $('#select').find('tr');
  
    dataset.show();
    
    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">


<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table>

最佳答案

只使用表而不是选择

var dataset = $('table').find('tr');

$(document).ready(function($) {
 
  $('#select').change(function() {
   
    var selection = $(this).val();
     var dataset = $('table').find('tr');
  
    dataset.show();
    
    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">


<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table>

关于javascript - 如何使用select dropdown过滤表td值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47666566/

相关文章:

javascript - jQuery UI 可排序和容器缩放

jquery - 使输入不可选择

javascript - Three.JS 动画在 Chrome v61 Mac OS X Sierra 上不显示

c# - Kendo UI 网格中的内联编辑?

javascript - 如何在 javascript/css 中删除窗口的边距或填充?

html - 坚持我的页脚页面的响应能力

html - 如何在 css 中制作图片作为我的背景

javascript - 如何获取附加按钮中的数据 ID?

javascript - 在 React 中渲染两个彼此相邻的组件

javascript - 如何引用克隆元素上的子元素