问题是:在我对父行进行排序时,我希望将Child行与父项一起移动。 我使用这个js来排序我的表数据。我的HTML就像
<table>
<tr class="parent">
<th id="apple">Apple</th>
<th id="orange">Orange</th>
<th>Banana</th>
</tr>
<tr class="parent">
<td>Apple</td>
<td>Orange</td>
<td>Banana</td>
</tr>
<tr class="child">
<td>Apple 1</td>
<td>Orange 1</td>
<td>Banana 1</td>
</tr>
<tr class="child">
<td>Apple 2</td>
<td>Orange 2</td>
<td>Banana 2</td>
</tr>
<tr class="parent">
<td>Table</td>
<td>cHAIR</td>
<td>Mouse</td>
</tr>
<tr class="child">
<td>Table 1</td>
<td>cHAIR 1</td>
<td>Mouse 1</td>
</tr>
<tr class="child">
<td>Table 2</td>
<td>cHAIR 2</td>
<td>Mouse 2</td>
</tr>
</table>
js是这样的:
jQuery.fn.sortElements = (function(){
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function(){return this;};
var placements = this.map(function(){
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing its original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i){
placements[i].call(getSortable.call(this));
});
};
})();
添加另一个JS:
$('#apple, #orange')
.each(function(){
var th = $(this),
thIndex = th.index(),
inverse = false;
th.click(function() {
// sorting classes don't work here b/c this function gets called repeatedly - moved to afterRequest: function
table.find('tr.parent td').filter(function(){
return $(this).index() === thIndex;
}).sortElements(function(a, b){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function(){
// parentNode is the element we want to move
return this.parentNode;
// this.parentNode
});
inverse = !inverse;
});
});
答案 0 :(得分:5)
假设您的sortElements正常工作。在排序之前创建一个关联,并在排序后追加到父级后面:
//the sort logic
//add association before sort
$(".parent").each(function(i,node){
var child=$(this).nextUntil('.parent');
$(this).data("child-node",child);
//sort
}).sortElements(function(a,b){
var lengthb= $(b).children("td").first().text().length
var lengtha= $(a).children("td").first().text().length
return lengthb-lengtha;
//append child
}).each(function(i,node){
var child=$(this).data("child-node");
$(this).after(child);
});
答案 1 :(得分:3)
我不确定我是否理解你的问题。
这可用于选择所有下一行是子项。
$(".parent").nextUntil($("tr").not(".child"))
您还可以通过添加.addBack()
在选择器中包含父级$(".parent").nextUntil($("tr").not(".child")).addBack()
答案 2 :(得分:3)
由于你已经在构建jQuery,我建议你研究DataTables jQuery插件,因为他们已经为你做了很多这类工作。你只需要进行配置。