问题是:在我对父行进行排序时,我希望将Child行与父项一起移动.
我正在使用这个js来排序我的表数据.我的 HTML就像
我正在使用这个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; }); });
解决方法
假设您的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); });