如何编辑此表过滤器脚本以按选定的列进行过滤? [英] How to edit this table filter script to filter by selected columns?
问题描述
我正在使用此脚本:
(function(document) {
'use strict';
var LightTableFilter = (function(Arr) {
var _input;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('light-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
LightTableFilter.init();
}
});
})(document);
和此输入:
<input type="search" class="light-table-filter" data-table="order-table">
当我在过滤器输入中键入内容时,它将过滤一个表,因此我只能看到其中有与文本匹配的条目.像这样: http://codepen.io/chriscoyier/pen/tIuBL 我如何编辑此脚本,以便它不按整个表过滤,而仅按某些选定的列过滤?就像前三列可能是我需要过滤的内容.
When I type something in the filter input, it filters a table so I see only entries I have in there matching the text. Like this: http://codepen.io/chriscoyier/pen/tIuBL How can I edit this script so it does not filter by the whole table, but instead only by some selected columns? Like maybe the first three columns is what I need to filter through.
推荐答案
我将添加data属性以配置可搜索的列.例如HTML可能是这样的:
I would add data attribute to configure what columns are searchable. For example HTML could be like this:
<input type="search" class="light-table-filter"
data-table="order-table"
data-table-columns="0,2" placeholder="Filter">
在上面的配置索引0和2中,名称"和电话"列是可过滤的.
In the above config indexes 0 and 2 tell that "Name" and "Phone" columns are filterable.
然后在JS部分中,您可以执行以下操作(仅限修改后的功能):
Then in JS part you can do something like this (only modified functions):
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
var columns = (_input.getAttribute('data-table-columns') || '').split(',');
Arr.forEach.call(tables, function (table) {
Arr.forEach.call(table.tBodies, function (tbody) {
Arr.forEach.call(tbody.rows, function (row) {
_filter(row, columns);
});
});
});
}
function _filter(row, columns) {
var text, val = _input.value.toLowerCase();
if (columns.length) {
columns.forEach(function (index) {
text += ' ' + row.cells[index].textContent.toLowerCase();
});
} else {
text = row.textContent.toLowerCase();
}
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
演示: http://codepen.io/anon/pen/zxVagm
这篇关于如何编辑此表过滤器脚本以按选定的列进行过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!