jquery sort element with array value

梦想的初衷 提交于 2020-01-13 12:06:23

问题


I need to sort some elements depend on it attribute. For an example:

<div id="sort">
<div n="1"></div>
<div n="2"></div>
<div n="3"></div>
<div n="4"></div>
</div>

And array_num

{3, 2, 1, 4}

pseudo code:

$('#sort').sort(array_num, 'n');

results will be:

<div id="sort">
<div n="3"></div>
<div n="2"></div>
<div n="1"></div>
<div n="4"></div>
</div>

回答1:


​var order = [3, 2, 4, 1]​;
var el = $('#sort');
var map = {};

$('#sort div').each(function() { 
    var el = $(this);
    map[el.attr('n')] = el;
});

for (var i = 0, l = order.length; i < l; i ++) {
    if (map[order[i]]) {
        el.append(map[order[i]]);
    }
}

Full code here ​




回答2:


untested...

$.fn.asort = function (order, attrName) {
    for(var i = 0, len = order.length; i < len; ++i) {
        this.children('[' + attrName + '=' + order[i] + ']').appendTo(this);
    }
}



回答3:


I stumbled across this trying to fix what I was after. I took @shrikant-sharat's method and added a little to it as the attribute I needed to sort on was actually on a child element. Thought I'd add here in case it helps anyone (and for future me!)

$.fn.asort = function (order, attrName, filter) {
  console.log(this.length, order.length, order);
  for(var i = 0, len = order.length; i < len; ++i) {

    if(typeof(filter) === 'function') {
      filter(this.children(), attrName, order[i]).appendTo(this);
    } else {
      this.children('[' + attrName + '=' + order[i] + ']').appendTo(this);
    }
  }
  return this.children();
}

It allows you to pass a filter function to match the element you're after. It's not the most efficient I suppose, but it works for me, e.g.:

$('.my-list').asort(mapViewOrder, 'data-nid', function(items, attrName, val) {
  return items.filter(function(index, i) {
    return ($(i).find('[' + attrName + '="' + val + '"]').length);
  });
});


来源:https://stackoverflow.com/questions/3563370/jquery-sort-element-with-array-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!