无法找到任何关于使用jquery tmpl()进行分组的示例,所以我认为id会发布我想出的内容(有效)以防其他人试图这样做。
答案 0 :(得分:2)
有关模板的基本用法,请参阅JQuery API docs。
我已经为此功能编写了一个扩展程序,允许对多个类别进行分组。
用法:
$(
JQuery模板 ).tmpl_sort(
数据 ,
[选项 ,
] 群组 )
•对于 JQuery模板,数据和选项,请参阅tmpl API documentation。
•组数组应该是一个由识别组的字符串组成的数组。
代码:
(function($){
$.fn.tmpl_sort = function(data, options_or_groups, array_groups){
return $.tmpl_sort(this, data, options_or_groups, array_groups);
}
$.tmpl_sort = function(template, data, options_or_groups, array_groups){
if(typeof array_groups == "undefined"){
array_groups = options_or_groups;
options_or_groups = void 0;
}
array_groups = typeof array_groups == "string" || typeof array_groups == "number" ? [array_groups] : array_groups;
if(!(array_groups instanceof Array)) throw new TypeError("$.fn.tmpl_sort: second argument has to be a string or array");
var groups = {};
for(var i=0; i<array_groups.length; i++){
(function(groupname){
var last;
groups[groupname] = function(group){
/* === is a strict comparison operator */
return last === (last=group);
}
})(array_groups[i]);
}
return template.tmpl(data, groups, options_or_groups)
}
})(jQuery);
的示例
var Leagues = [
{ League: 1, Group: "A", Team: "France" },
{ League: 1, Group: "A", Team: "China" },
{ League: 1, Group: "B", Team: "Brazil" },
{ League: 2, Group: "A", Team: "England" },
{ League: 2, Group: "A", Team: "Scotland" },
{ League: 2, Group: "B", Team: "India" }
];
$("#itemtemplate").tmpl_sort(Leagues, ["sameleague", "samegroup"]).appendTo("#lvList");
答案 1 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<style type="text/css">
#lvList { float:left; }
.league { background-color: #E8F6FF; }
.group { background-color: #FEEAEB; margin-left: 10px; }
.team { margin-left: 20px; }
</style>
</head>
<body>
<script id="itemtemplate" type="text/x-jquery-tmpl">
{{if !$item.sameasbefore("League") }}
<div class="league">League: ${League}</div>
{{/if}}
{{if !$item.sameasbefore("Group") }}
<div class="group">Group: ${Group}</div>
{{/if}}
<div class="team">${Team}</div>
</script>
<div id="lvList"></div>
<script type="text/javascript">
var Leagues = [
{ League: 1, Group: "A", Team: "France" },
{ League: 1, Group: "A", Team: "China" },
{ League: 1, Group: "B", Team: "Brazil" },
{ League: 2, Group: "A", Team: "England" },
{ League: 2, Group: "A", Team: "Scotland" },
{ League: 2, Group: "B", Team: "India" }
];
var grouping = [];
$("#itemtemplate").tmpl(Leagues, {
sameasbefore: function (field) {
var same = false;
if (grouping[field] === this.data[field])
same = true;
grouping[field] = this.data[field];
return same;
}
}).appendTo("#lvList");
</script>
</body>
</html>