我很难弄清楚如何根据数据属性中的一个键/值对对对列表进行排序。
<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());
}
}
});