2017-06-17 4 views
2

テーブルで並べ替えを使用しようとしています。私は以下のメソッドを使用していますが、メソッドを使用して数値をソートする際にエラーがあります。この方法は適切に機能しますが、数字ASCとDESCの順序で発行されます。私はなぜこれを起こすのか分からなかった。みんな、これについて何か考えている?javascriptで数字を並べ替える方法

function sortTable(n, selector) { 
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; 
///table = document.getElementById(selector); 
table = $(selector); 
switching = true; 

//Set the sorting direction to ascending: 
dir = "asc"; 
/*Make a loop that will continue until 
no switching has been done:*/ 
while (switching) { 
    //start by saying: no switching is done: 
    switching = false; 
    rows = $(table).find('tr'); ///table.getElementsByTagName("TR"); 
    /*Loop through all table rows (except the 
    first, which contains table headers):*/ 
    for (i = 0; i < (rows.length - 1) ; i++) { 
     //start by saying there should be no switching: 
     shouldSwitch = false; 
     /*Get the two elements you want to compare, 
     one from current row and one from the next:*/ 
     x = rows[i].getElementsByTagName("TD")[n]; 
     y = rows[i + 1].getElementsByTagName("TD")[n]; 
     /*check if the two rows should switch place, 
     based on the direction, asc or desc:*/ 
     if (x != null && y != null) { 
      if (dir == "asc") { 
       if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { 
        //if so, mark as a switch and break the loop: 
        shouldSwitch = true; 
        break; 
       } 
      } else if (dir == "desc") { 
       if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) { 
        //if so, mark as a switch and break the loop: 
        shouldSwitch = true; 
        break; 
       } 
      } 
     } 
    } 
    if (shouldSwitch) { 
     /*If a switch has been marked, make the switch 
     and mark that a switch has been done:*/ 
     rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); 
     switching = true; 
     //Each time a switch is done, increase this count by 1: 
     switchcount++; 
    } else { 
     /*If no switching has been done AND the direction is "asc", 
     set the direction to "desc" and run the while loop again.*/ 
     if (switchcount == 0 && dir == "asc") { 
      dir = "desc"; 
      switching = true; 
     } 
    } 
} 
} 
+0

.find( 'TR')'は 'table.rows'を使用することは非常にはるかに効率的で、そして代わりに、'行[i]との。 getElementsByTagName( "TD")[n] '行[i] .cells [n]'とみなします。他に何も入力しないでください。 ;-)これはバブルソートであり、非常に非効率的です。ソートする行を配列に入れ、* Array.prototype.sort *を使用してソートし、ソート順に並べ替えることを検討してください。 – RobG

答えて

2

あなたが任意の特定の列を使用して表の行をソートし、ソート番号など、アレイにソートする行を置くことによって、内蔵Array.prototype.sort方法を活用することができますしたい場合は、並べ替え次に、行を必要な順序でテーブルに配置します。例えば:

function sortMe(evt) { 
 
    var table = this;   // Table clicked on 
 
    var cell = evt.target;  // Cell clicked on 
 
    var col = cell.cellIndex; // Column number 
 
    
 
    // Put rows into an array 
 
    var rowArray = [].slice.call(table.rows); 
 
    // Or for ECMAScript 2015 
 
    // var rowArray = Array.from(table.rows); 
 

 
    // Sort rows 
 
    rowArray.sort(function(a, b) { 
 
    
 
    // Get values of col to sort on 
 
    a = a.cells[col].textContent; 
 
    b = b.cells[col].textContent; 
 

 
    // If numeric, sort as number 
 
    if (isNumeric(a)) { 
 
     return a - b; 
 
    } 
 
    // Other sort options here, e.g. as dates 
 
    // Otherwise, sort as string 
 
    return a.localeCompare(b); 
 
    }); 
 
    
 
    // Put rows back in table in order 
 
    var tbody = table.tBodies[0]; 
 
    rowArray.forEach(function (row) { 
 
    tbody.appendChild(row); 
 
    }) 
 

 
} 
 

 
// Helper function 
 
// Check if value is numeric, '2' returns true 
 
function isNumeric(n) { 
 
    return !isNaN(parseFloat(n)) && isFinite(n); 
 
} 
 

 
// Attach listener to table 
 
window.onload = function() { 
 
    document.querySelector('table').addEventListener('click', sortMe, false); 
 
}
table { 
 
    border-collapse: collapse; 
 
} 
 
td { 
 
    border: 1px solid #bbbbbb; 
 
    width: 5em; 
 
}
<table> 
 
    <tr><td>A<td>3 
 
    <tr><td>D<td>0 
 
    <tr><td>B<td>1 
 
    <tr><td>C<td>2 
 
</table>

任意の列でクリックすると、列がソートされます。ヘッダーとフッターの追加、昇順と降順の切り替え、空白セルの処理などの追加を行うことができます。

ヘッダーセルでクラスまたはデータ属性を使用して、使用する並べ替えのタイプ。代わりに `$(テーブル)の

0

var filter=''; 
 

 
function myFunction() { 
 
    var input, ul, li, a, i; 
 
    input = document.getElementById("myInput"); 
 
    filter = input.value.toUpperCase(); 
 
    var product = object.filter(filterByID) 
 
    console.log(product); 
 
} 
 

 

 

 
function filterByID(item) { 
 

 
    if (item.First_Name.toUpperCase().indexOf(filter) > -1) { 
 
     return true; 
 
    } 
 
    return false; 
 
} 
 

 
var object = [ 
 
    { 
 
    "First_Name": "Adele", 
 
    }, 
 
    { 
 
    "First_Name": "Neeraj", 
 
    }, 
 
    { 
 
    "First_Name": "Nitin", 
 
    }, 
 
]
* { 
 
    box-sizing: border-box; 
 
} 
 

 
#myInput { 
 
    background-image: url('/css/searchicon.png'); 
 
    background-position: 10px 12px; 
 
    background-repeat: no-repeat; 
 
    width: 100%; 
 
    font-size: 16px; 
 
    padding: 12px 20px 12px 40px; 
 
    border: 1px solid #ddd; 
 
    margin-bottom: 12px; 
 
} 
 

 
#myUL { 
 
    list-style-type: none; 
 
    padding: 0; 
 
    margin: 0; 
 
} 
 

 
#myUL li a { 
 
    border: 1px solid #ddd; 
 
    margin-top: -1px; /* Prevent double borders */ 
 
    background-color: #f6f6f6; 
 
    padding: 12px; 
 
    text-decoration: none; 
 
    font-size: 18px; 
 
    color: black; 
 
    display: block 
 
} 
 

 
#myUL li a.header { 
 
    background-color: #e2e2e2; 
 
    cursor: default; 
 
} 
 

 
#myUL li a:hover:not(.header) { 
 
    background-color: #eee; 
 
}
<h2>My Phonebook</h2> 
 

 
<input type="text" id="myInput" oninput="myFunction()" placeholder="Search for names.." title="Type in a name">

関連する問題