通过下拉值对表进行排序(简化我的代码)

我有一张桌子。 我希望用户能够通过他们在给定下拉列表中选择的选项来过滤表格。 我有它的工作,但它很麻烦,很难添加新的行(不能让它在jsfiddle工作,抱歉http://jsfiddle.net/anschwem/Y4cf6/2/ )。 任何简化的代码将不胜感激。 此外,如果此代码仅限于过滤某个表,那将是很好的,所以我可以有很多表和许多下拉。 如果这可以在没有行ID的情况下完成,甚至更好。 谢谢! 我的表/ html:

cats
cats
dogs
birds
dogs
Select... Cats Dogs Birds

码:

   $(window).load(function(){ $('select').change(function() { if($('#selectFilter option:selected').attr('id') == "sel_All" || $('#selectFilter option:selected').attr('id') == "sel_All"){$('#catRow').show();$('#catRow2').show();$('#dogRow').show();$('#dogRow2').show();$('#birdRow').show();} if($('#selectFilter option:selected').attr('id') == "selCats" || $('#selectFilter option:selected').attr('id') == "selCats"){$('#catRow').show();$('#catRow2').show();$('#dogRow').hide();$('#dogRow2').hide();$('#birdRow').hide();} if($('#selectFilter option:selected').attr('id') == "selDogs" || $('#selectFilter option:selected').attr('id') == "selDogs"){$('#catRow').hide();$('#catRow2').hide();$('#dogRow').show();$('#dogRow2').show();$('#birdRow').hide();} if($('#selectFilter option:selected').attr('id') == "selBirds" || $('#selectFilter option:selected').attr('id') == "selBirds"){$('#catRow').hide();$('#catRow2').hide();$('#dogRow').hide();$('#dogRow2').hide();$('#birdRow').show();}  

请在此处找到重构代码“ http://jsfiddle.net/5fZv7/3/ ”,代码片段如下所示。

HTML代码:

  
cats
cats 2
dogs
birds

和JavaScript代码:

  $(document).load(function () { $('#selectFilter').change(function () { $(".all").hide(); $("." + $(this).find(":selected").attr("id")).show(); }); }); 

希望这有助于您轻松高效地维护代码。

我重构了你的小提琴: http : //jsfiddle.net/Y4cf6/4/

通过利用CSS类和内置属性(如“value”),我们可以轻松地使这些代码更通用。

对于这个HTML:

 
Cat 1
Cat 2
Dog 1
Cat 3
Bird 1
Cat 4
Dog 2

Javascript简化为单行:

 $("#selectFilter").on("change", function() { $("#animals").find("tr").hide().filter("." + $(this).val()).show(); }); 

编辑:这个不能处理的一个案例是给你一种再次显示所有行的方法。 我将此作为练习留给您,但这里有一个提示:您可以读取$(this).val()的值,如果没有值,则显示所有行而不是过滤它们。

您可以像这样更改您的html标记

 
cats
cats
dogs
birds
dogs

那你的jQuery

 $('#selectFilter').change(function(){ var trs = $('#animal tr'); if(this.value == ''){ // if first option picked show all trs.show(); }else{ var $el = $('.'+this.value); // element to show trs.not($el).hide(); // hide all but the elements to show $el.show(); // show elements } }); 

小提琴

您应该查看DataTables ,它内置了这种过滤( API中的 fnFilter)

起初可能有点学习曲线,但最终会更加灵活。