I have X amount of divs in a page, each div item represents a single product and looks like this:
<div class="productContainer">
<li>
<img src="my-product-image.jpg"></a>
<div class="productInfo">
<h4>
<!-- SORT ALL DIVS BASED ON A TAG CONTENT -->
<a class="productTitleForSorting" href="product-page-link">NAME</a><br>
</h4>
<div class="product-price">
<span id="lowestPrice">PRICE:
<!-- OR SORT ALL DIVS BY PRODUCT PRICE SPAN CONTENT -->
<span class="productPriceForSorting">$XX.XX</span></span>
</div>
</div>
</li>
</div>
Then I have a select list / dropdown list from where I'd like to sort the divs by price or alphabetically.
For example, let's say I have 10 divs (10 products), like the one above on a single page. I would like to be able to sort either by title (a.productTitleForSorting content), or by price (span.productPriceForSorting) on select list change.
Any ideas how I can go about accomplishing this with Javascript / jQuery? It开发者_运维百科 has to be done on the client side.
I tried using a datasort plugin, but no luck with that one, so looking for new ideas and suggestions. Thanks!
I would not recommend sorting and reordering the dom. If it has to be done on client side then store the javascript array and sort that. For example:
var items = [{price:3,name:"something"}, {price:10,name:"somethingelse"}];
Now use JavaScript sort functions to sort this and append to the dom. This is much more efficient than moving around dom objects.
you can use the native sort function, but the thing is that you have to provide a comparison mechanism:
function sortByPrice(a,b){
return $(a).find('.productPriceForSorting').text() > $(b).find('.productPriceForSorting').text();
}
then you can sort your elements by using:
$('.productContainer').sort(sortByPrice);
After you've sorted the elements, you need to update the html, so you should empty the product container and then append the sorted elements in the new order :
function reorderEl(el){
var container = $('#productList');
container.html('');
el.each(function(){
$(this).appendTo(container);
});
}
Putting it all toghether :
reorderEl($('.productContainer').sort(sortByPrice));
here's a working example: http://jsfiddle.net/gion_13/jKJc3/
Using something like this sorting plugin, you just need comparator functions like:
function sortByTag(a, b) {
$(a).find('a').first().text() > $(b).find('a').first().text();
}
精彩评论