最近剛好在進行一些網頁設計的工作,其中有牽扯到資料表格排序的問題,一般都是直接在query資料庫時直接排序,或是用php排序,但是只要重新排序一次就等於網頁重新讀取一次(重新做一次計算),所以就想利用 Jquery(javascript) 來減少資源的消耗。
這邊就分享一個簡單的Jquery(javascript)通用表格排序的程式。
程式原理:
此程式主要是排序已經存在的html table,先讀取每個表格內的內容然後做排序,最後在修改原本表格的內容。
使用方法:
0.假設目前網站有兩個表格
Name |
Score |
Stella |
85 |
Andy |
100 |
Melo |
59 |
Sophie |
95 |
Alice |
55 |
Name |
Score |
Marry |
100 |
Apple |
85 |
Melo |
59 |
Sophie |
95 |
Alice |
55 |
1.先引入jquery
2.將程式載入
<script type="text/javascript">
/**************** Javascript function with jquery ***************
Function name: table_sort([select_table_name])
Author: Andy
History:
2012/03/22 First relased at AirNote
****************************************************************/
function table_sort(select){
var table_data = new Array()
$(select+" tr:gt(0)").each(function(){
var i = table_data.length
table_data[i] = new Array()
$(this).find("td").each(function(){
var j = table_data[i].length
table_data[i][j] = new Object()
table_data[i][j].value = $(this).html()
table_data[i][j].className = $(this).attr("class")
if(table_data[i][j].className == undefined)
table_data[i][j].className = ""
if(table_data[i][j].value == undefined)
table_data[i][j].value = ""
})
})
var sort_asc = 1;
$(select+" tr:eq(0) td,"+select+" tr:eq(0) th").click(function(){
sort_asc *= -1
var idx = $(this).index()
var sort_type = (table_data[0][idx].value[0].charCodeAt(0) > 47 && table_data[0][idx].value[0].charCodeAt(0) < 58) ? "num":"text"
table_data.sort(function(a,b){
if(a[idx].value == "")
return (-1)*sort_asc
if(sort_type == "num"){
return (a[idx].value - b[idx].value)*sort_asc
}else{
var compare_length = a[idx].value.length > b[idx].value.length ? a[idx].value.length : b[idx].value.length
for(var i=0;i < compare_length;i++){
var a_code = a[idx].value.charCodeAt(i)
var b_code = b[idx].value.charCodeAt(i)
if(a_code == b_code && i == (compare_length - 1))
return (a[idx].value.length > b[idx].value.length ? -1 : 1)*sort_asc
else if(a_code != b_code)
return (a_code - b_code)*sort_asc
}
}
})
var i = 0
var j = 0
$(select+" tr:gt(0)").each(function(){
$(this).find("td").each(function(){
$(this).html(table_data[i][j].value)
$(this).attr("class",table_data[i][j].className)
j++
})
j=0
i++
})
})
}
</script>
3.呼叫設定排序
function table_sort("#mytable")
參數為選取表格的名稱,用法與CSS選擇相同,請使用#選擇 Id name
EX: #myTable
這樣套用的表格,點擊最上面一列就可以整欄排序
$(function(){//網頁讀取完後
table_sort("#myTable")//參數為選取表格的名稱,用法與CSS選擇相同,請使用#選擇 Id name EX: #myTable
table_sort("#myTable2")
})
4. 完成!!
=====觀看範例=====
PS
1. 此程式會自動判斷欄位的第一個字元,為數字則數字排列,為文字則文字排列。
還有其他問題的話都可以發問喔!!
Tags
table sort, query, javascript, web design, html
沒有留言:
張貼留言