0

我有一系列看起来像这样的生成产品

<div class="product"><div class="productImage" title="one"></div></div>
<div class="product"><div class="productImage" title="two"></div></div>
<div class="product"><div class="productImage" title="three"></div></div>
<div class="product"><div class="productImage" title="four"></div></div>

有没有办法可以将它们放在一个数组中以使用 javascript 以不同的顺序显示它们?

想不通。有什么建议吗?

what I have right now
<div class="product">
    <div class="productImage" title="Elixer Altima">product image goes here with other shopping features</div>
</div>
<div class="product">
    <div class="productImage" title="Bain Oleo Relax">product image goes here with other shopping features</div>
</div>
<div class="product">
    <div class="productImage" title="Satin">product image goes here with other shopping features</div>
</div>
<div class="product">
    <div class="productImage" title="Hair Cream">product image goes here with other shopping features</div>
</div>

New Order to be
<div class="product">
    <div class="productImage" title="Hair Cream">product image goes here with other shopping features</div>
</div>
<div class="product">
    <div class="productImage" title="Satin">product image goes here with other shopping features</div>
</div>
<div class="product">
    <div class="productImage" title="Bain Oleo Relax"></div>
</div>
<div class="product">
    <div class="productImage" title="Elixer Altima">product image goes here with other shopping features</div>
</div>
4

3 回答 3

0

Assume you want titles in alphabetic order .

var $items= $('.product').detach();

$('#container').append( $items.sort( sortTitles));


function sortTitles(a,b){
    return a.title > b.title ? 1 :-1;

}

Adjust sort function for other attributes as required

于 2012-12-26T03:04:29.653 回答
0

You can sort based on the text, html, attributes and more if you like. For instnace, if you wanted to sort based on the alphabetical order of the titles themselves, the following would work (I've added a #products parent element for demonstration purposes):

$("#products .product").sort(function(a,b){
    var _a = $(a).text(), _b = $(b).text();
    return _a > _b ? 1 : -1;
})​.appendTo("#products");​​​​

Fiddle: http://jsfiddle.net/yxCWd/

In your case, it appears you just want to reverse the natural order. This could be done any number of ways. One such way would be to use the .reverse method on the Array prototype to reverse the order of a collection, and then re-append the elements to their parent:

var container = $("#products");
container.append(container.find(".product").get().reverse());​

Calling .get converts our collection to an array, thus giving us the ability to call .reverse.

Fiddle: http://jsfiddle.net/yxCWd/2/

于 2012-12-26T03:06:09.683 回答
0

我很幸运这个http://james.padolsey.com/javascript/sorting-elements-with-jquery/

于 2012-12-26T02:43:47.547 回答