我有一个这样的头:
<thead>
<tr>
<th rowspan="2">Cell-1</th>
<th rowspan="2">Cell-2</th>
<th colspan="3">Header</th>
<th rowspan="2">Cell-6</th>
</tr>
<tr>
<th">Cell-3</th>
<th">Cell-4</th>
<th">Cell-5</th>
</tr>
</thead>我需要创建一个jquery选择器,其中单元格的顺序是1-2-3-4-5-6。现在我的选择器看起来像这样:
hdrCols = thead.find( "tr:first th[rowspan=2], TR:first TH[rowspan=2]").add( thead.find( "tr:last-child th, TR:last-child TH" ) );这给了我1-2-6-3-4-5,打破了我的布局。
有没有办法创建一个选择器,让单元格按正确的顺序排列?我不能移动列,所以任何解决方案都必须包含这一点。
发布于 2012-02-26 19:30:54
尝试简单地使用JavaScripts sort()函数。像这样:http://jsfiddle.net/6wYQt/
function sortHeaders(a, b) {
var x = $(a).text().toLowerCase();
var y = $(b).text().toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
thead = $('thead');
hdrCols = thead.find( "tr:first th[rowspan=2], TR:first TH[rowspan=2]").add( thead.find( "tr:last-child th, TR:last-child TH" ) );
hdrCols.sort(sortHeaders);
console.log(hdrCols);
发布于 2012-02-26 19:31:29
我会尝试将选定的元素放入一个数组中,然后编写自己的函数对该数组进行排序。因此,第一步,获取元素并将它们放入一个数组中:
var elements = thread.find("th");
var elements_array = [];
elements.each(function(){
elements_array.push($(this));
});...then一个自定义函数,尝试对它们进行排序:
function custom_sort(a, b)
{
// these elements are TH jQuery objects...
var content_a = a.text();
var content_b = b.text();
// perform string comparison, for example...
// return -1 if a comes before b, 1 if b comes before a, and
// 0 if they're equal...
return (a < b ? -1 : (a > b ? 1 : 0));
}
// finally sort the array of elements...
elements_array.sort(custom_sort);这应该可以做到这一点,尽管我假设TH元素需要根据它们的内容进行排序,所以这就是我在排序中实现字符串比较的原因,尽管您可以将其替换为所需的任何内容!希望这能有所帮助!
发布于 2012-02-26 19:58:33
如果您需要在不添加属性和具有可排序列名的情况下执行此操作,您可以尝试这样做:
function extractTableHeader($table) {
var $thead = $table.find('thead'),
$row1 = $thead.children().first(),
$children1 = $row1.children(),
$row2 = $row1.next(),
$children2 = $row2.children(),
cells = [[],[]];
// map first row
$children1.each(function(){
var $th = $(this),
rows = $th.prop('rowspan'),
cols = $th.prop('colspan'),
_rows = rows > 1,
_cols = cols > 1;
while (cols) {
cells[0].push(_cols ? null : this);
if (!_rows) {
cells[1].push(cells[0].length - 1);
}
cols--;
}
});
$.each(cells[1], function(i, o){
cells[0][o] = $children2[i];
});
return $(cells[0]);
}
$(function() {
var $th = extractTableHeader($('table')),
order = [];
$th.each(function(){
order.push($(this).text());
});
console.log(order.join(', '));
});
// output: Cell-1, Cell-2, Cell-3, Cell-4, Cell-5, Cell-6https://stackoverflow.com/questions/9452605
复制相似问题