我有一些数据存储在一个表中,我想使用 Javascript 进行过滤。我在输入字段中键入我的过滤器字符串,并仅显示匹配的行。
但是现在,我想这样做:例如,如果我在筛选字段中键入 value1|value2
,我只需要与这两个字符串匹配的行(value1 AND value2
)。我已经尝试了很多方法来做到这一点,但没有人完全按照我的意愿去做......
这是我用来过滤的示例(适用于一个字符串):
function filterFromName(text) {
// Variables
var filter, tableData, tr, td, i;
filter = text.toUpperCase();
tableData = document.getElementById('data_values');
tr = tableData.getElementsByTagName('tr');
// For each table row, hide those who don't match the search text
for (i = 0; i< tr.length; i++) {
td = tr[i].getElementsByTagName('td')[1]; // query the Alias column
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1)
tr[i].style.display = "";
else
tr[i].style.display = "none";
}
}
}
有没有办法调整这段代码来做我想做的事?
最佳答案
But now, I would like to do this : for example, if I type "value1|value2" in my filter field, I want only rows which match with these 2 strings (value1 AND value2).
您需要将您的逻辑更改为(内联评论)
function filterFromName(text) {
var tableData, tr, td, i;
var filterParams = text.toUpperCase().split( "|" ); //split by | to get array of search parameters
tableData = document.getElementById('data_values');
tr = tableData.getElementsByTagName('tr');
// For each table row, hide those who don't match the search text
for (i = 0; i< tr.length; i++) {
td = tr[i].getElementsByTagName('td')[1]; // query the Alias column
if (td) {
var tdValue = td.innerHTML.toUpperCase();
var isMatched = filterParams.filter( function( val ){ return tdValue.indexOf( val ) > -1 }); //check if any val in filterParam array is matching the tdValue
if ( isMatched.length ) //check length of filtered resultset
tr[i].style.display = "";
else
tr[i].style.display = "none";
}
}
}
关于javascript - 具有多个值的表过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47157065/