JavaScript implements table filtering and javascript table Filtering
Use JavaScript to implement Table filtering and design a Filterable Table.
After makeAllTablesFilterable is applied, each table is appended with an input field. After the user inputs the characters, the rows that do not contain the characters in the table will disappear, leaving only the rows that contain the corresponding characters, the corresponding characters are highlighted.
Effect:
Filter. js:
"Use strict"; window. onload = function () {var tables = getAllTables (); makeAllTablesFilterable (tables) ;}; // use the following two rows for embedding .. // var tables = getAllTables (); // makeAllTablesFilterable (tables); function getAllTables () {return document. getElementsByTagName ("table");} // highlight function heightlight (node, keyword) {node. innerHTML = node. innerHTML. replace (new RegExp (keyword, "g"), "<span class = 'heightlight'>" + keywor D + "</span>") ;}// clear the highlighted function clearHeightlight (node) {node. innerHTML = node. innerHTML. replace (/<span class = \ "heightlight \">/g ,""). replace (/<\/span>/g, "");} // restore the display function showAllTr (table) {var tr = table. getElementsByTagName ("tr"); for (var I = 1; I <tr. length; I ++) {tr [I]. hidden = false ;}/// enables the list to be able to filter 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]; // search for keywords. if no keyword exists, hide 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:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
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");}/* highlighted keyword, the same as firefox highlight */. heightlight {background-color: #38D878; color: white; border: none; padding: 0 ;}