简体   繁体   English

Javascript,按数字或字母对列进行排序

[英]Javascript, sort columns by numbers or letters

I am trying to get different columns in a table to sort. 我试图获取表中的不同列进行排序。 I have them working for numbers but I don't know how to get it done for columns with alphabetical data. 我让他们为数字工作,但我不知道如何对具有字母数据的列进行处理。

Here is what I am working on: http://jsfiddle.net/nx4Ex/1/ 这是我正在从事的工作: http : //jsfiddle.net/nx4Ex/1/

Based on this: https://stackoverflow.com/a/7558600/2219915 基于此: https : //stackoverflow.com/a/7558600/2219915

I would have asked in a comment there but my rep is not high enough. 我会在那儿发表评论,但我的代表不够高。

This is the script I am using. 这是我正在使用的脚本。 I know parsefloat deals with numbers but I'm not sure how I would change it to work with numbers and/or letters. 我知道parsefloat处理数字,但是我不确定如何将其更改为使用数字和/或字母。

function sortTable(){
var tbl = document.getElementById("caltbl").tBodies[0];
var store = [];
for(var i=0, len=tbl.rows.length; i<len; i++){
    var row = tbl.rows[i];
    var column1 = parseFloat(row.cells[0].textContent || row.cells[0].innerText);
    if(!isNaN(column1)) store.push([column1, row]);
}
store.sort(function(x,y){
    return x[0] - y[0];
});
for(var i=0, len=store.length; i<len; i++){
    tbl.appendChild(store[i][1]);
}
store = null;
};

I also should mention that I am trying to avoid using any javascript libraries or plugins. 我还应该提到,我试图避免使用任何JavaScript库或插件。 All I need is this basic sorting functionality. 我需要的只是此基本排序功能。

The sorting of table, build using plain JavaScript. 表的排序,使用纯JavaScript构建。 I tested in chrome 我用铬测试

$('sort-date').addEventListener('click', function(){
    sortByDate( this );
},false);

$('sort-notify').addEventListener('click', function(){
    sortByNotify( this );
},false);

$('sort-id').addEventListener('click', function(){
    sortById( this );
},false);   

Clicking on column heading , sort the table contents . 单击列标题,对表内容进行排序。 jsfiddle jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM