根据数组中填充的排序顺序对html进行排序

Sort html from a sort order populated in an array

本文关键字:排序 顺序 html 数组 填充      更新时间:2023-09-26

我试图排序一个html列表的距离,我想把距离属性在我的标记。我所做的是,我渲染商店列表html,在js中我创建了一个数组,我保持商店和距离。

locations = [];
locations.push({
    'store': stores[i],
    'cordinate': Math.random()
});

我用这个

排序
locations.sort(dynamicSort('cordinate'));
function dynamicSort(property) {
  var sortOrder = 1;
  return function(a, b) {
    var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
    return result * sortOrder;
  }
}

这里是我卡住的地方,我如何使用这个数组排序我的html ?这里的关键是我不想因为在那里设置坐标而使我的html混乱。

我的小提琴就在这里


编辑
问题是关于用数组中填充的排序顺序对输出html进行排序。在那里,我删除了html和其他js,因为我懒得填充标记。

基本上,您需要做的就是按排序顺序调用在html元素上追加

这将把元素附加在html元素的末尾。

var sortHTML = function(locations) {
  $.each(locations, function(i, location) {
    var targetElement = $('#' + location.store.id);
    targetElement.parent().append(targetElement)
  });
};
sortHTML(locations);

提琴在这里:https://jsfiddle.net/wbcj026x/1/