我很难弄清楚如何根据数据属性中的键/值对之一对列表进行排序。
<ul>
<li data="{name:'Foo', number: '1'}">
<h3>Foo</h3>
</li>
<li data="{name:'Bar', number: '2'}">
<h3>Bar</h3>
</li>
</ul>
这是 jQuery。我正在设置元数据属性并访问它。所有这些都运行良好。
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"}
});
)};
示例:我需要按名称升序排序。有人能指出我正确的方向吗?
编辑:
这是我用来触发排序的表单:
<form name="filterForm">
Sort:
<select name="sort" size="1">
<option value="nameAsc" <cfif URL.sort EQ 1>selected="selected"</cfif>>Name A to Z</option>
<option value="nameDesc" <cfif URL.sort EQ 2>selected="selected"</cfif>>Name Z to A</option>
<option value="numberAsc" <cfif URL.sort EQ 3>selected="selected"</cfif>>Number 1-10</option>
<option value="numberDesc" <cfif URL.sort EQ 4>selected="selected"</cfif>>Number 10-1</option>
</select>
</form>
还有 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 有一个排序函数,可以将函数作为参数。当您进行自定义比较时应该使用此函数。请参阅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());
});
编辑:更新了上面的语法。每个循环 - 修复语法错误
编辑:更正了最后一个循环中的错误
EDIT2:根据请求,我正在使用比较功能进行更新
function compare(a, b){
return a.name - b.name;
}
关于jquery - 根据数据属性对列表进行排序(使用 jquery 元数据插件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258974/