2014-09-29 84 views
0

我已经找到并按照此处的示例对表格进行排序,但不起作用。这里是我的代码:使用jQuery对表格排序

function comparer(index) { 
return function (a, b) { 
    var valA = getCellValue(a, index), valB = getCellValue(b, index); 
    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB); 
} 
} 

function getCellValue(row, index) { 
return $(row).children('td').eq(index).html(); 
} 

function sortTable(header) { 
var table = $(this).parents('table').eq(0); 
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())); 
this.asc = !this.asc; 
if (!this.asc) { 
    rows = rows.reverse(); 
} 
for (var i = 0; i < rows.length; i++) { 
    table.append(rows[i]); 
} 
} 

function createTableHeader(table, headers, alignment) { 
if (headers.length > 0) { 
    var thead = document.createElement('thead'); 
    table.appendChild(thead); 
    var tr = document.createElement('tr'); 
    for (var i = 0; i <= headers.length - 1; i++) { 
     var th = document.createElement('th'); 
     var text = document.createTextNode(headers[i]); 
     th.appendChild(text); 
     th.style.textAlign = alignment; 
     th.setAttribute('onclick', sortTable) 
     tr.appendChild(th); 
    } 
    thead.appendChild(tr); 
} 
} 

无任何响应,然而,当我看到的细节,我可以看到连接到TH元素的功能。有任何想法吗?

这个事实,我正在动态地创建这个表与从AJAX调用收到的数据有什么关系的问题?

+0

的方法给click处理程序绑定到元素不会有以下几个原因工作。 'onclick'应该是最后的手段。阅读事件处理 – charlietfl 2014-09-29 10:31:52

+0

有没有必要重新发明轮子,当有插件可以做这项工作:) http://tablesorter.com/docs/ – Terry 2014-09-29 10:34:35

+0

@charlietfl我该怎么做这种排序不使用头部的点击事件? – 2014-09-29 10:49:32

回答

0

这里是我做过什么,使其工作:

function createTableHeader(table, headers, alignment) { 
if (headers.length > 0) { 
    var thead = document.createElement('thead'); 
    table.appendChild(thead); 
    var tr = document.createElement('tr'); 
    for (var i = 0; i <= headers.length - 1; i++) { 
     var th = document.createElement('th'); 
     var text = document.createTextNode(headers[i]); 
     th.appendChild(text); 
     th.style.textAlign = alignment; 
     th.style.cursor = 'pointer'; 
     th.setAttribute('title', "Sort by " + headers[i]); 
     th.onclick = function() { 
      var rows = $(table).find('tbody').find('tr').toArray().sort(comparer($(this).index())); 
      this.asc = !this.asc; 
      if (!this.asc) { 
       rows = rows.reverse(); 
      } 
      for (var i = 0; i < rows.length; i++) { 
       $(table).append(rows[i]); 
      } 
     } 
     tr.appendChild(th); 
    } 
    thead.appendChild(tr); 
} 
}