按自定义排序顺序对jQuery中的Div进行排序 [英] Sorting Divs in jQuery by Custom Sort Order

查看:677
本文介绍了按自定义排序顺序对jQuery中的Div进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过将
的类别属性与Javascript $ b $中的类别顺序进行比较来重新排序标记输入的子元素b变量 category_sort_order 。然后我需要删除其类别属性
未出现在 category_sort_order 中的div。

I'm trying to re-sort the child elements of the tag input by comparing their category attribute to the category order in the Javascript variable category_sort_order. Then I need to remove divs whose category attribute does not appear in category_sort_order.

预期结果应该是:


任何

product1

product2

下载

any
product1
product2
download

代码:

<div id="input">
<div category="download">download</div>
<div category="video">video1</div>
<div category="video">video2</div>
<div category="product">product1</div>
<div category="any">any</div>
<div category="product">product2</div>
</div>

<script type="text/javascript">
var category_sort_order = ['any', 'product', 'download'];
</script>

我真的不知道从哪里开始这个任务但是如果你能提供任何帮助无论如何我都会非常感激。

I really don't even know where to begin with this task but if you could please provide any assistance whatsoever I would be extremely grateful.

推荐答案

我写了一个jQuery插件来做这种事情,可以很容易地适应你的用例。

I wrote a jQuery plugin to do this kind of thing that can be easily adapted for your use case.

原始插件在这里

这是您的问题的改进

(function($) {

$.fn.reOrder = function(array) {
  return this.each(function() {

    if (array) {    
      for(var i=0; i < array.length; i++) 
        array[i] = $('div[category="' + array[i] + '"]');

      $(this).empty();  

      for(var i=0; i < array.length; i++)
        $(this).append(array[i]);      
    }
  });    
}
})(jQuery);

并使用如此

var category_sort_order = ['any', 'product', 'download'];
$('#input').reOrder(category_sort_order);

这次恰好可以获得产品的正确订单,因为product1出现在原始列表中的product2之前,但在放入数组并附加到DOM之前,可以轻松更改类别。此外,如果将它用于许多元素,可以通过一次性附加数组中的所有元素而不是迭代数组并一次附加一个元素来改进它。这可能是 DocumentFragments 的好例子。

This happens to get the right order for the products this time as product1 appears before product2 in the original list, but it could be changed easily to sort categories first before putting into the array and appending to the DOM. Also, if using this for a number of elements, it could be improved by appending all elements in the array in one go instead of iterating over the array and appending one at a time. This would probably be a good case for DocumentFragments.

这篇关于按自定义排序顺序对jQuery中的Div进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆