如何使用JQUERY订购div
我有这样的div:
Pagás
$ 67 Valor
$ 160 Descuento $ 93
我想通过“ofertapagas”中的值或“ofertavalor”中的值或“ofertadescuento”中的值来订购具有class =“oferta”的div,我不知道如何,我不能使用数据库,我只是可以使用Jquery,我正在使用它的最新版本。 请帮忙!!
jQuery摘要Array.prototype.sort
。 由于jQuery wrappet集是类似于Array的对象 ,因此您可以在它们上调用.sort()
或对它们应用sort。
var $datosoferta = $('.datosoferta'); $datosoferta.children().detach().sort(function(a,b) { return +a.textContent.split(/\$/)[1].trim() - +b.textContent.split(/\$/)[1].trim(); }).appendTo($datosoferta);
请参见http://typeofnan.blogspot.com/2011/02/did-you-know.html
演示 : http : //jsfiddle.net/Rfsfs/
用ui。 JQuery UI – 可排序的演示和文档
为了你的代码;
$( ".offer" ).sortable({ update: function(event, ui) { // do post server. } });
如果你把那些提供DIV放在某种容器(另一个DIV?)中,你可以获取所有的提议并按照他们孩子的价值排序。
在下面的HTML中,我将商品div放在容器div中,并为包含data-value
每个子div添加了一个data-value
属性,以便于访问(不需要正则表达式)。
Pagá $ 67 Valor $ 130 Descuento $ 93 Pagá $ 57 Valor $ 150 Descuento $ 43 Pagá $ 107 Valor $ 250 Descuento $ 1000 Pagá Valor Descuento
JS / jQuery函数:
ofertas_sort = function(sort_key) { // array of offer divs var ofertas = $('.infoferta'); // the div classname corresponding to the key by which // we are sorting var sort_key_sel = 'div.' + sort_key; // in large lists it'd be more efficient to calculate // this data pre-sort, but for this instance it's fine ofertas.sort(function(a, b) { return parseInt($(sort_key_sel, a).attr('data-value')) - parseInt($(sort_key_sel, b).attr('data-value')); }); // re-fill the container with the newly-sorted divs $('#ofertas_container').empty().append(ofertas); };
这是jsFiddle上的代码,在HTML底部有一些链接来演示排序: http : //jsfiddle.net/hans/Rfsfs/2/
我更改了一些值以使排序更加明显。