Sort a table by drop down values (simplify my code)

前端 未结 4 1954
小蘑菇
小蘑菇 2021-01-23 17:37

I have a table. I want the user to be able to be able to filter the table by the option they pick in a given drop down. I have it working, but it\'s messy and hard to add new ro

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-23 18:11

    I've refactored your fiddle: http://jsfiddle.net/Y4cf6/4/

    By taking advantage of CSS classes and built-in attributes like "value", we can easily make this code more generic.

    For this HTML:

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

    The Javascript is reduced to essentially a one-liner:

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

    Edit: the one case this doesn't handle is giving you a way to show all the rows again. I'll leave this as an exercise for you, but here's a tip: You could read the value of $(this).val(), and if there isn't a value, then show all the rows instead of filtering them.

提交回复
热议问题