我有这个页面:
<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升序或降序,我该怎么做?
答案 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>
尽管jQuery和下划线共同存在,如果你只需要为这个排序加载两个库而没有别的东西,那么就会加载几个超出代码的kb-s。