基于数据属性的排序列表(使用jquery元数据插件)

我很难确定如何根据data属性中的一个键/值对来排序列表。

  • Foo

  • Bar

这是jQuery。 我正在设置元数据attr并访问它。 所有这一切都很好。

 jQuery.metadata.setType("attr", "data"); $(document).ready(function(){ // loop through each list item and get the metadata $('ul li').each(function () { console.log($(this).metadata()); // shows the following - Object {name="Foo", number="1"} }); )}; 

示例:我需要按名称升序排序。 有人能指出我正确的方向吗?

编辑:

这是我用来触发排序的表单:

 
Sort: <option value="nameAsc" selected="selected">Name A to Z <option value="nameDesc" selected="selected">Name Z to A <option value="numberAsc" selected="selected">Number 1-10 <option value="numberDesc" selected="selected">Number 10-1

以及处理更改事件的jquery,但我不确定我是否正确实现了Mikael Eliasson的代码,因为我不确定在哪里传递所选内容的值:

 $('form[name=filterForm] select').change(function(){ var sortBy = this.value; var arr = [] // loop through each list item and get the metadata $('ul li').each(function () { var meta = $(this).metadata(); meta.elem = $(this); arr.push(meta); }); arr.sort(appendItems()); function appendItems(){ //Foreach item append it to the container. The first i arr will then end up in the top $.each(arr, function(index, item){ item.elem.appendTo(item.elem.parent()); } } }); 

Javascript有一个sort函数,可以将函数作为参数。 当您进行自定义比较时,应该使用此函数。 请参见http://www.w3schools.com/jsref/jsref_sort.asp

所以我要做的就是这样的事情

 var arr = [] // loop through each list item and get the metadata $('ul li').each(function () { var meta = $(this).metadata(); meta.elem = $(this); arr.push(meta); }); arr.sort(compare); //Foreach item append it to the container. The first i arr will then end up in the top $.each(arr, function(index, item){ item.elem.appendTo(item.elem.parent()); }); 

编辑:上面.each循环的更新语法 – 修复语法错误

编辑:更正了最后一个循环中的错误

EDIT2:根据请求我正在使用比较function进行更新

 function compare(a, b){ return a.name - b.name; }