我已经在网上搜索过,但我还没有找到解决方案。也许我搜索了错误的术语,所以如果我的问题的解决方案可能非常简单,我很抱歉。
所以,我想做的是以下内容:
那么,我怎样才能做到这一点?
提前致谢。
答案 0 :(得分:3)
我创建了准备使用组件(需要纯js no Jquery),并按列值过滤表行。组件使用数据属性,可以自定义过滤任何列。
var FilterSelect=function(selectSelector,tableSelector){
this.$select=document.querySelector(selectSelector);//our select
this.$table=document.querySelector(tableSelector); //our table
this.filter=null; //filter value
this.columnNum=null; //column num to check value
this._bind();
//run setting and filtering in beginning ( option can be set )
this._setAndFilter();
};
// method sets parameters from chosen option
FilterSelect.prototype._set=function(){
var option=this.$select.options[this.$select.selectedIndex];//get current option
this.filter=typeof option.dataset.filter!='undefined'?option.dataset.filter:null;
this.columnNum=typeof option.dataset.columnNum!='undefined'?option.dataset.columnNum:null;
};
//method filters table
FilterSelect.prototype._filterTable=function(){
var trs=this.$table.querySelectorAll("tr");
for (var i=0; i<trs.length; i++){
var tr=trs[i];
if (this.columnNum==null){
//no filters
tr.style.display="block"
continue;
}
var td=tr.querySelectorAll("td")[parseInt(this.columnNum)];//get td
var value=td.innerText;//get td inner text to compar
if (value!=this.filter)
tr.style.display="none"; //filter does not match - hide
else
tr.style.display="block";//display block - filter match
}
};
//filtering table and setting options
FilterSelect.prototype._setAndFilter=function(){
this._set();//set current filter and column
this._filterTable();//do table filtering
};
//bind select change event
FilterSelect.prototype._bind=function(){
this.$select.addEventListener("change",function(){
this._setAndFilter();
}.bind(this));
};
//usage
var filterSelect=new FilterSelect('#select','#table');
&#13;
<select id="select">
<option>No filter</option>
<option data-column-num="3" data-filter="E">Filter Label E</option>
<option data-column-num="2" data-filter="Yes">Filter Available</option>
<option data-column-num="3" data-filter="F">Filter Label F</option>
<option data-column-num="2" data-filter="No">Filter Not Available</option>
</select>
<table id="table">
<tr>
<td>1</td><td>One</td> <td>Yes</td><td>E</td>
</tr>
<tr>
<td>2</td><td>Two</td> <td>Yes</td><td>F</td>
</tr>
<tr>
<td>3</td><td>Three</td> <td>No</td><td>E</td>
</tr>
</table>
&#13;
有关数据属性的信息:
data-column-num
- 要检查过滤器值的列数(从0开始)
data-filter
- 用于检入由columnNum列选择的文本内的过滤器值
以上组件可以按单列值进行过滤。以下是可以过滤多列的组件 - https://jsfiddle.net/maciejsikora/0kbubfts/