PAYATHON 2026

根据选中值用 filter 函数过滤表格数据

数据小陈

结论:不需要用 .bind()。先把 select.value 读进变量,再在 Array.prototype.filter() 的谓词里使用;也可以写一个返回谓词的工厂函数。filter 回调只接收 (element, index, array),不会把控件当作 this。.bind() 能工作,但只是把 this 强行指向控件,耦合更重。

为什么 .bind() 能工作

Array.prototype.filter() 调用回调时不会把 select 设为 this。传入的函数里用了 this.querySelectorAll,所以得用 .bind(colour) 把 this 固定到控件上。更直接的做法是先用 colour.value 读出当前选中值,再在箭头函数里使用。读取时机要分清:如果谓词之后还会复用,就在谓词内部读取 select.value;如果想捕获当前值,就在调用 filter 前读取。

单控件示例

HTML:

<select id='colour'>
  <option value=''>全部</option>
  <option value='blue'>blue</option>
  <option value='red'>red</option>
  <option value='yellow'>yellow</option>
</select>
<table>
  <thead>
    <tr><th>id</th><th>item</th><th>colour</th></tr>
  </thead>
  <tbody id='tbody_output'></tbody>
</table>

JS:

const data = [
  { id: 0, item: 'ball', colour: 'blue' },
  // ...
];

const colourSelect = document.getElementById('colour');
const tbody = document.getElementById('tbody_output');

function getFilteredData() {
  const selectedColour = colourSelect.value;
  return data.filter(item => selectedColour === '' || item.colour === selectedColour);
}

function renderTable() {
  tbody.innerHTML = getFilteredData()
    .map(item => `<tr><td>${item.id}</td><td>${item.item}</td><td>${item.colour}</td></tr>`)
    .join('');
}

colourSelect.addEventListener('change', renderTable);
renderTable();

判断“全部”时,建议写 selectedColour === ”,这比 !selectedColour 稳妥。值可能是 ‘0’ 或 ‘false’ 时,!value 会误判。空选项最好显式写上 value=”。

多个控件:用配置和工厂函数

const filters = [
  { select: document.getElementById('colour'), field: 'colour' },
  // { select: document.getElementById('item'), field: 'item' },
];

function applyFilters(rows) {
  return rows.filter(row =>
    filters.every(({ select, field }) => {
      const value = select.value;
      return value === '' || row[field] === value;
    })
  );
}

function render() {
  const rows = applyFilters(data);
  tbody.innerHTML = rows
    .map(item => `<tr><td>${item.id}</td><td>${item.item}</td><td>${item.colour}</td></tr>`)
    .join('');
}

filters.forEach(({ select }) => select.addEventListener('change', render));
render();

如果希望每个控件生成一个独立谓词:

function makeFilter(select, field) {
  return row => select.value === '' || row[field] === select.value;
}

const predicates = filters.map(({ select, field }) => makeFilter(select, field));
const rows = data.filter(row => predicates.every(fn => fn(row)));

这样就不用 .bind(),以后加过滤控件也方便。

注意事项

  • 不要把过滤函数挂到 DOM 元素上,用普通函数或配置对象会更清楚。
  • 不要依赖 id 自动生成的全局变量,改用 document.getElementById 或 querySelector 获取元素。
  • 用模板字符串拼 innerHTML 时,若数据来自用户输入,要防 XSS。可以改用 textContent 或 DOM API 创建节点。
  • 数据量很大时,频繁重建整个表格可能卡顿,可以考虑 DocumentFragment、虚拟列表或分页。

备注:内容仅供参考。