我看到一些奇怪的行为与正在呈现选择的optgroups和选项的顺序有关。我有一些数据用于在select中构建optgroup,然后使用下划线js _grouby函数进行选项。 Firefox以我订购json的方式呈现数据,Chrome和IE以相反的顺序显示它。
HTML:
<select name="dropdownlist" id="dropdownlist">
<option value="All">All</option>
</select>
JavaScript的:
$(document).ready(function() {
var dataresults = [{"MonthName":"April","Month":4,"Year":2014,"Date":"\/Date(1397451600000)\/"},{"MonthName":"January","Month":1,"Year":2014,"Date":"\/Date(1388556000000)\/"},{"MonthName":"November","Month":11,"Year":2013,"Date":"\/Date(1384322400000)\/"},{"MonthName":"July","Month":7,"Year":2013,"Date":"\/Date(1373864400000)\/"}];
BindYearDropDown(dataresults);
function BindYearDropDown(data)
{
var groupData = _.groupBy(data, function (obj) {
return obj.Year;
});
var optGroups = [];
for (var key in groupData) {
if (groupData.hasOwnProperty(key)) {
var optGroup = $("<optgroup></optgroup>");
optGroup.attr("label", key);
optGroup.attr("id", key);
var currentGroup = groupData[key];
for (var i = 0; i < currentGroup.length; i++) {
$("<option />").attr("value", currentGroup[i].Month).html(currentGroup[i].MonthName).appendTo(optGroup);
}
optGroups.push(optGroup);
}
}
//optGroups.reverse();
for (var i = 0; i < optGroups.length; i++) {
$('#dropdownlist').append(optGroups[i]);
}
};
FireFox结果:(这就是我想要显示数据的方式)
Chrome结果:
IE11结果:
提前致谢,
KC
答案 0 :(得分:3)
如果您真的想使用您提供的结构中的数据,可以创建一个年份列表,然后对其进行排序。否则,我建议@mu建议太短。 jsfiddle
/* reusable descending sort function */
function sortDescending(value) {
return value * -1;
};
...
var groupData = _.groupBy(data, function (obj) {
return obj.Year;
});
/* Sort the years in descending order */
var years = _.sortBy(_.keys(groupData), sortDescending);
var optGroups = [];
for (var index in years) {
var key = years[index];
...