1

我一直在寻找一种强大而简单的方法来对我的案例研究进行排序,但是经过几个小时并搜索堆栈溢出后,我找不到一种方法来按照我想要的方式过滤案例研究。

基本上我会使用 css 类给每个案例研究三个类别(生产年份、项目类型和名称),例如标记看起来像这样

<div class="name1 home 2013"></div>
<div class="name2 work 2012"></div>
<div class="name3 home 2012"></div>
<div class="name4 charity 2012"></div>
<div class="name5 home 2010"></div>
<div class="name6 work 2007"></div>

然后我想要有按钮,这样你就可以选择你想要对案例研究进行排序的类别。所以类似的东西。

<div class="button" id="year">Sort by Year</div>
<div class="button" id="alpha">sort Alphabetically</div>
<div class="button" id="type">sort by type</div>

这就是我卡住的地方。我可以创建什么 javascript 函数,这样如果您单击“按年份排序”按钮,它将创建一个看起来像这样的标记。例如,将所有案例研究分类到具有同一年案例研究的 div 中。

<div>
   <div class="name1 home 2013"></div>
</div>

<div>
<div class="name2 work 2012"></div>
<div class="name3 home 2012"></div>
<div class="name4 charity 2012"></div>
</div>

<div>
<div class="name5 home 2010"></div>
</div>

<div>
<div class="name6 work 2007"></div>
</div>
4

1 回答 1

2

I would use data attributes to make the filtering easier.

<div class="name1 home" data-year="2013">2013</div>
<div class="name2 work" data-year="2012">2012</div>
<div class="name3 home" data-year="2012">2012</div>
<div class="name4 charity" data-year="2012">2012</div>
<div class="name5 home" data-year="2010">2010</div>
<div class="name6 work" data-year="2007">2007</div>

The using JQuery and array.map (could be replaced with a foreach if you want older browser support)

var studies = $('[data-year]')

studies.map(function(index, el) {
    var $el = $(el)
    year = $el.attr('data-year')
    if($('#' + year).length == 0){
        $(document.body).append(
            $('<div>').attr('id', year)
            .css('margin-bottom', '20px')
        )
    }

    $('#' + year).append(el)
 })

what this does is take all the elements with a data-year attribute, foreach element check to see if a div with the id of that elements year exists. If it doesn't create one and append it to the body. Then it appends the element into the year container.

see this jsfiddle

于 2013-02-10T16:04:12.883 回答