简体   繁体   English

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

[英]Sorting content after page loads

i have this page: 我有此页面:

<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>

i was wondering if there is a way to sort the product-# divs by their .product-info.product-title ascending or descending with javascript, how can i do that? 我想知道是否有一种方法可以按它们的.product-info.product-title用JavaScript升序或降序对product-#div进行排序,我该怎么做?

Id use jQuery to catch all product elements and underscore javascript to sort. ID使用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/ http://jsfiddle.net/jL4dX/3/

Although jQuery and underscore rock together, if you need to load both libraries only for this sorting and nothing else, it would be couple of kb-s of excess code loaded. 尽管jQuery和下划线在一起,但是如果您只需要为这种排序加载两个库而别无其他,则将加载多余的kb-s。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM