2016-12-07 90 views
1

我很難根據項目類中的值篩選項目。項目必須始終從最高值到最低值排序。根據類中的值篩選項目

例Item視圖:<div id="mt-138" class="id[138] rating[8.1] views[350] item">item1</div>

id = Last added Item 
rating = Top Rated Item 
views = Most Viewd Items 

我使用一個簡單的下拉菜單:

<div class="dropdown"> 
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Filter 
    <span class="caret"></span></button> 
    <ul class="dropdown-menu"> 
    <li><a id="last-added" href="#">Last added</a></li> 
    <li><a id="top-rated" href="#">Top rated</a></li> 
    <li><a id="most-viewed" href="#">Most viewed</a></li> 
    </ul> 
</div> 

jsfiddle

回答

1

 $(function() { 
 
      $('.dropdown-menu a').click(function() { 
 
       var triggerId = $(this).attr('id'); 
 
       $('.item').detach().sort(function (thisElement, otherElement) { 
 
        var pattern = '\\[(\\d+(\\.\\d+)*)\\]'; 
 
        switch(triggerId) 
 
        { 
 
         case 'last-added': 
 
          pattern = 'id' + pattern; 
 
          break; 
 
         case 'top-rated': 
 
          pattern = 'rating' + pattern; 
 
          break; 
 
         case 'most-viewed': 
 
          pattern = 'views' + pattern; 
 
          break; 
 
        } 
 
        var regex = new RegExp(pattern); 
 
        var thisValue = regex.exec($(thisElement).attr('class'))[1]; 
 
        var otherValue = regex.exec($(otherElement).attr('class'))[1]; 
 
        return otherValue - thisValue; 
 
       }).appendTo('body'); 
 
      }); 
 
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<div class="dropdown"> 
 
     <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> 
 
      Filter 
 
      <span class="caret"></span> 
 
     </button> 
 
     <ul class="dropdown-menu"> 
 
      <li><a id="last-added" href="#">Last added</a></li> 
 
      <li><a id="top-rated" href="#">Top rated</a></li> 
 
      <li><a id="most-viewed" href="#">Most viewed</a></li> 
 
     </ul> 
 
    </div> 
 
    <div id="mt-138" class="id[138] rating[8.1] views[50] item">item1</div> 
 
    <div id="mt-139" class="id[139] rating[8] views[350] item">item2</div> 
 
    <div id="mt-140" class="id[140] rating[7.9] views[35] item">item3</div>