如果我有几个div:

<div data-sort='1'>div1</div>
<div data-sort='4'>div4</div>
<div data-sort='8'>div8</div>
<div data-sort='12'>div12</div>
<div data-sort='19'>div19</div>

And I dynamically create the divs:

<div data-sort='14'>div1</div>
<div data-sort='6'>div1</div>
<div data-sort='9'>div1</div>

我怎样才能让他们在不必重新加载所有div的情况下,按顺序对已加载的div进行排序?

I think that I would need to build an array of the data-sort values of all of the divs on the screen, and then see where the new divs fit in, but I am not sure if this is the best way.

推荐答案

Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

您可以在添加新div后调用此函数.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

Jquery相关问答推荐

如果在视窗中有相同的数据属性值,则jQuery/添加类

如何在Jquery和Laravel中使用请求传递两个参数给Datatable

我需要在上一个表格单元格中显示计算结果

将日期时间从 javascript 传递给 c# (Controller)

bootstrap 模式中的自动完成问题

为什么对同一个 ASP.NET MVC 操作的多个同时 AJAX 调用会导致浏览器阻塞?

$.post 和 $.ajax 之间的区别?

模糊事件阻止点击事件工作?

将 HTML5 Canvas 转换为要上传的文件?

使用 jQuery click 处理锚点 onClick()

jquery - 单击事件不适用于动态创建的按钮

以ajax方式在rails 3中提交表单(使用jQuery)

jQuery Keypress 箭头键

JSLint 消息:未使用的变量

jQuery $.cookie 不是一个函数

jQuery Button.click() 事件被触发两次

Twitter Bootstrap css 类的 jQuery show() 隐藏

如何在 Bootstrap 中创建切换按钮

JQuery 判断 DOM 中的重复 id

为什么我应该创建异步 WebAPI 操作而不是同步操作?