我有几个对象包含对 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/