简体   繁体   English

从填充在数组中的排序顺序对 html 进行排序

[英]Sort html from a sort order populated in an array

I'm trying to sort a html list by a distance, I do not want to put distance property in my markup.我想通过一个距离排序HTML列表,我希望把距离属性在我的标记。 What I do is that I render the store list html, in js I create a array where I keep the store and distance.我所做的是渲染商店列表 html,在 js 中创建一个数组,在其中保留商店和距离。

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

I sort that with this我用这个排序

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;
  }
}

Here is where I get stuck, how can I sort my html using this array?这是我卡住的地方,如何使用这个数组对我的 html 进行排序? The key here is that I don't want to clutter my html with setting the cordinate there.这里的关键是我不想在那里设置坐标来弄乱我的 html。

My fiddle is right here我的小提琴就在这里


EDIT编辑
The question was about sorting the output html with the sort order populated in a array.问题是关于使用填充在数组中的排序顺序对输出 html 进行排序。 There for I removed the html and other js that I only used because of being lazy to populate markup.在那里,我删除了 html 和其他 js,因为我懒得填充标记。

Basically all you need to do, is call append on the html elements in the sort order.基本上你需要做的就是按排序顺序在 html 元素上调用append

This will append the element in the end of the html elements.这会将元素附加到 html 元素的末尾。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM