JavaScript實現表格過濾
用JavaScript實現表格過濾,設計一個Filterable Table。
應用makeAllTablesFilterable之後,每個table附加一個輸入欄位,使用者輸入字元之後,table中不包含這些字元的rows將消失,僅剩下含有相應字元的rows,並且相應字元會反白。
效果:
filter.js:
"use strict";window.onload = function () { var tables = getAllTables(); makeAllTablesFilterable(tables);};//嵌入的話用下面兩行..// var tables = getAllTables();// makeAllTablesFilterable(tables);function getAllTables() { return document.getElementsByTagName("table");}//高亮顯示function heightlight(node, keyword) { node.innerHTML = node.innerHTML.replace(new RegExp(keyword,"g"),""+keyword+"");}//清除高亮function clearHeightlight(node) { node.innerHTML = node.innerHTML.replace(//g, "").replace(/<\/span>/g, "");}//恢複顯示function showAllTr(table) { var tr = table.getElementsByTagName("tr"); for (var i = 1; i < tr.length; i++) { tr[i].hidden = false; }}//讓列表變得可能夠過濾function makeFilterable(table) { var input = document.createElement("input"); input.oninput = function() { clearHeightlight(table); showAllTr(table); //過濾詞為空白則直接返回 if (!this.value) return; for (var i = 1; i < table.getElementsByTagName("tr").length; i++) { var tr = table.getElementsByTagName("tr")[i]; //尋找是否含有關鍵字,不含有則隱藏 if ( tr.innerHTML.indexOf(this.value) == -1) { tr.hidden = true; continue; } for (var j = 0; j < tr.cells.length; j++) heightlight(tr.cells[j], this.value); } }; table.parentNode.insertBefore(input,table); return table;}function makeAllTablesFilterable(tables) { for (var i = 0; i < tables.length; i++) makeFilterable(tables[i]);}
html:
<script type="text/javascript" src="filter.js"></script>
Filterable tableTo-Do
What? |
When? |
Location |
Paris Web 2007 |
2007-11-15 |
IBM La Defense / INSIA |
Paris On Rails 2007 |
2007-12-10 |
Cite des Sciences |
Burger Quiz party |
2007-04-14 |
Volta |
Staff
First name |
Last name |
Latest checkin |
Richard |
Piacentini |
2007-03-27 |
Eric |
Daspet |
2007-03-28 |
Aurore |
Jaballah |
2007-03-15 |
filter.css:
table, tr *{ border: 1px solid gray; margin: 0; padding: 3px; border-collapse: collapse;}tr:nth-child(even),tr:hover { background-color: #DEDEDE;}th { text-align: left; background-color: #041A7F; color: white; font-weight: bold; padding-right:16px;}.ascend, .descend { background-color: #A4B0FC; background-position: right; background-repeat: no-repeat;}.ascend { background-image: url("ascend.png");}.descend { background-image: url("descend.png");}/*高亮關鍵字,跟firefox的高亮一樣*/.heightlight { background-color: #38D878; color: white; border: none; padding: 0;}