我有以下 DOM 结构,我想根据 data-created
进行排序属性。
<a id="comment-34" href="#"/>
<li data-created="12342342" />
<a id="comment-35" href="#"/>
<li data-created="89342342" />
<a id="comment-36" href="#"/>
<li data-created="45363342" />
我无法(出于各种原因)将 <a>
包裹起来和<li>
在外<div>
。我想做 javascript 排序。如果我只有 <li>
,所有 jQuery 排序插件都可以进行排序。 。例如。使用tinysort jQuery插件(http://tinysort.sjeiti.com/)我可以做到
$('li').tsort({order:'desc', attr:'data-created'});
但是排序后发生的情况是 <a>
不再与原来的 sibling 有联系。我也评价过https://github.com/jamespadolsey/jQuery-Plugins/tree/master/sortElements/但它可能会遇到同样的问题。
有办法做到这一点吗?同样,我无法包装 <a>
和<li>
在外<div>
。我也不想动态包装 <div>
这样我就可以使用 tsort 了。
任何干净的解决方案:-)?
最佳答案
这样的东西应该适合你:
var elms = [];
$('a').each(function() { //create the array of a and li
var pair = {
aTag: $(this),
liTag: $(this).next("li")
};
elms.push(pair);
});
$("a, li").detach(); //detach them from the dom
elms.sort(function(a, b) {
return a.liTag.data("created") < b.liTag.data("created"); //sort based upon the created data
});
$.each(elms , function(){
$("ul").append(this.aTag).append(this.liTag); //push them back to the dom.
});
jsfiddle 上的代码示例.
关于javascript - 在 DOM 中按相邻元素排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5410942/