[英]Filtering table row by select option
我有一個要使用選擇選項進行過濾的表,但無法弄清楚如何返回並顯示初始過濾器后的所有數據。 我也需要幫助來干燥我的代碼。
// SHOWS INDIVIDUAL FILTER BUT CAN'T SHOW ALL
$(document).ready(function($) {
$("#sortAwardType").change(function() {
$("table").show();
var selection = $(this).val().toUpperCase();
var dataset = $(".awards-body").find("tr");
dataset.show();
if(selection) {
dataset.filter(function(index, item) {
// Filter shows table row with the word 'General'
return $(item).find(":contains('General')").text().toUpperCase().indexOf(selection) === -1;}).hide();
} else {
// .all corresponds to a "Show All" option. When selected the data doesn't show
$("#sortAwardTable").change(function(){
$(".all").dataset.show();
});
}
});
});
// ATTEMPTING DRY CODE. NOW I CAN'T FILTER AT ALL
$(document).ready(function($) {
$("#sortAwardType").change(function() {
$("table").show();
var selection = $(this).val().toUpperCase();
var dataset = $(".awards-body").find("tr");
var match = [
":contains('General')",
":contains('Free')",
":contains('Regional')",
":contains('Demographic')"];
dataset.show();
if(selection) {
dataset.filter(function(index, item) {
return $(item).find(match).text().toUpperCase().indexOf(selection) === -1;}).hide();
} else {
// .all corresponds to a "Show All" option. When selected I want all data to show but instead it only shows an empty table (header present but no rows)
$("#sortAwardTable").change(function(){
$(".all").dataset.show();
});
}
});
});
我不想僅重復if block
來更改":contains('_____')"
。 我嘗試將它們分組到一個數組中,然后將它們分配給var match
,但是過濾器不起作用。
salam,您只需將所有包含選擇器放在同一字符串中
$(item).find(":contains('General'),:contains('Free'),:contains('Regional'),:contains('Demographic')").
但如果您想放輕松,請遵循我的前任:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="searchBox"> <table id='testTable'> <tr > <td>aa</td> <td>bb</td> <td>cc</td> </tr> <tr > <td>ab</td> <td>bc</td> <td>cd</td> </tr> <tr > <td>zz</td> <td>ee</td> <td>ff</td> </tr> </table> <script> $('#searchBox').keyup(function(){ var val = $(this).val().toLowerCase(); if(val ===""){ $("#testTable > tbody > tr").toggle(true); return; } $("#testTable > tbody > tr").toggle(false); $("#testTable").find("td").each(function(){ if($(this).text().toLowerCase().indexOf(val)>-1) $(this).parent().toggle(true); }); }); </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.