页面加载后对内容进行排序

时间:2013-01-22 12:00:56

标签: javascript html sorting

我有这个页面:

<div class="products">
    <div id="product-1" class="product">
        <a href="#" title="View this" class="product-a">
            <img class="product-img" src="/product.png" alt="Image of this product" /><span class="stilt"></span>
            <div class="product-info">
               <h3 class="product-title"><span>This Product</span></h3>
               <p class="product-price"><span>Product price</span></p>
            </div>
        </a>
    </div>

    <div id="product-2" class="product">
        <a href="#" title="View this" class="product-a">
            <img class="product-img" src="/product.png" alt="Image of this product" /><span class="stilt"></span>
            <div class="product-info">
               <h3 class="product-title"><span>This Product</span></h3>
               <p class="product-price"><span>Product price</span></p>
            </div>
        </a>
    </div>
    ...
</div>

我想知道是否有办法对产品进行排序 - #divs的.product-info.product-title使用javascript升序或降序,我该怎么做?

1 个答案:

答案 0 :(得分:4)

我使用jQuery来捕获所有产品元素并强调javascript以进行排序。

Products:
<div class="products">
    <div class="product">
        <div class="name">B name</div>
    </div>
    <div class="product">
        <div class="name">C name</div>
    </div>
    <div class="product">
        <div class="name">A name</div>
    </div>
</div>


<br/>

Sort Products:
    <button id="asc">Ascending</button>
    <button id="desc">Descending</button>

<script type="text/javascript">
    function sortList(dir) {
        var $products = $('.products .product');
        var sorted = _.sortBy($products, function(product){
            return $(product).find('.name').html();
        });
        if (dir == "desc") {
            sorted.reverse();
        }
        $('.products').append($(sorted));
    }

    $('#asc').click(function() {
        sortList('asc');
    });


    $('#desc').click(function() {
        sortList('desc');
    });
</script>

http://jsfiddle.net/jL4dX/3/

尽管jQuery和下划线共同存在,如果你只需要为这个排序加载两个库而没有别的东西,那么就会加载几个超出代码的kb-s。