简化Jquery过滤器脚本

时间:2014-07-16 06:43:41

标签: jquery filter

这个脚本可以简化,以便我不必专门定义类attr,以防万一添加其他类型。

JQuery

$(".devfilter select").change(function(){
  $( ".devfilter select option:selected").each(function(){
      if($(this).attr("value")==="Current"){
          $(".property.Upcoming").fadeOut("slow");
          $(".property.Completed").fadeOut("slow");
          $(".property.Current").fadeIn("slow");
        }
      if($(this).attr("value")==="Upcoming"){
          $(".property.Current").fadeOut("slow");
          $(".property.Completed").fadeOut("slow"); 
          $(".property.Upcoming").fadeIn("slow");
        }
      if($(this).attr("value")==="Completed"){
          $(".property.Current").fadeOut("slow");
          $(".property.Upcoming").fadeOut("slow");
          $(".property.Completed").fadeIn("slow");
      }
      if($(this).attr("value")==="*"){
          $(".property.Current").fadeIn("slow");
          $(".property.Upcoming").fadeIn("slow");
          $(".property.Completed").fadeIn("slow");
      }
  });
}).change();

HTML

<p class="devfilter">
<select name="development-filter">
    <option value="*">All</option>
    <option value="Current">Current</option>
    <option value="Upcoming">Upcoming</option>
    <option value="Completed">Completed</option>

   

<div class="more classes property Upcoming" data-type="Upcoming">Upcoming 1</div>
<div class="more classes property Current" data-type="Current">Current 1</div>
<div class="more classes property Completed" data-type="Completed">Completed 1</div>
<div class="more classes property Completed" data-type="Completed"> Completed  2</div>
<div class="more classes property Upcoming" data-type="Upcoming">Upcoming 2</div>
<div class="more classes property Current" data-type="Current">Current 2</div>

由于 说

2 个答案:

答案 0 :(得分:2)

由于select不允许multiple选择,因此无需在选项上使用$.each,您可以使用val()检索所选选项,然后构建像这样的选择器:

$(".devfilter select").change(function() {
    $(".property").fadeOut("slow");
    var value = $(this).val();
    var selector = value == '*' ? '.property' : '.property.' + value;
    $(selector).fadeIn("slow");
}).change();

Example fiddle

答案 1 :(得分:0)

试试这个

$(".devfilter select").change(function(){

  $( ".devfilter select option:selected").each(function(){

          $(".property").fadeOut("slow");
          $(".property"+"."+$(this).data("type")).fadeIn("slow");

  });
}).change();
相关问题