根据类中的值过滤项目

时间:2016-12-07 02:45:49

标签: jquery

我根据项目类中的值过滤项目时遇到困难。必须始终从最高值到最低值订购商品。

示例项目视图:<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 个答案:

答案 0 :(得分:1)

&#13;
&#13;
        $(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');
            });
        });
&#13;
<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>
&#13;
&#13;
&#13;