javascript - JQuery - 从对象排序 DOM

标签 javascript jquery

我有几个对象包含对 DOM 元素的引用:

var liObjs = [new Li($el1, price), new Li($el2, price), new Li($el3, price)]

// Li Model
function Li($element, price){
 var self = this;

 self.price = price; 
 self.$element = $element;
}

// My DOM Looks like this:
<ul>
 <li>Price: $3</li>
 <li>Price: $1</li>
 <li>Price: $2</li>
</ul>

而且我需要根据 liObjs 中的对象按价格对它们进行排序.

我已经设法对 liObjs 进行了排序基于每个对象的价格属性,但我无法为了我的生活而渲染它们。请帮忙。

注意: <li>s已经在 DOM 中创建,但我需要在页面加载时对它们重新排序。

最佳答案

非 jQuery 方式

// Remove existing elements from the parent node.
var parent = liObjs[0].$element.parentNode;

while (parent.hasChildNodes()) {
  parent.removeChild(parent.lastChild);
}

// Assuming you have already sorted the array
// you can simply loop through them and add them

liObjs.forEach(function(item) {
  parent.appendChild(item.$element);
});

jQuery 方式

$(liObjs[0].$element)
  .parent()
  .empty()
  .append(liObjs.map(function(item) {
    return item.$element;
  }));

这里有一个 CodePen 展示了它是如何工作的。
http://codepen.io/jessegavin/pen/NpavgZ?editors=1010

关于javascript - JQuery - 从对象排序 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818865/

相关文章:

jquery - 更改数据角色 ="header"中 .ui-title 的宽度

php - 如何从使用ajax的javascript函数获取值

Javascript 问题,需要根据 2 <select> 中的选择对表内的值进行着色

javascript - 将 Html 表转换为 JSON

javascript - 我的片段有什么不同? (Node.js 新手)

javascript - Jquery 动画可排序问题

javascript - 为什么向按钮添加类仅在第二次单击后才有效?

javascript - 引用以ajax形式加载当前正在执行的脚本的脚本标签

c# - 如何将多个属性从ajax post调用传递到aspx页面webmethod?

javascript - 如何获取我的App id(或POC id)?