js实现如下
// 设置升序还是降序,默认是升序
var flag=true;
function itemSort(){
// 1. 获得表格
var itemTable=document.getElementById("itemsTable");
// 2. 通过表格获得tbody
var itemTableBody=itemTable.tBodies[0];
// 3. 创建空数组
var arrItem=new Array()
// 4.把数据行拷贝到数组中
for(var i=0;i<itemTableBody.rows.length;i++){
arrItem[i]=itemTableBody.rows[i];
}
// 5.判断是升序还是降序,实现具体的排序功能
if(flag){
arrItem.sort(sortAsc);
}else{
arrItem.sort(sortDesc);
}
flag=!flag;
// 6. 创建文档碎片,用来保存已经排序之后的数据,以便于提高性能
var df = document.createDocumentFragment();
// 7. 把排序好的元素添加到碎片中
for(var i=0;i<arrItem.length;i++){
df.appendChild(arrItem[i]);
}
// 8. 把碎片条件并且替换原来的tbody中的数据
itemTableBody.appendChild(df)
}
function sortAsc(num1,num2){
// 获得制定行的某列的单元格的值
num1=parseInt(num1.cells[2].firstChild.nodeValue);
num2=parseInt(num2.cells[2].firstChild.nodeValue);
if(num1>num2){
return 1;
}else if(num1==num2){
return 0;
}else{
return -1;
}
}
function sortDesc(num1,num2){
num1=parseInt(num1.cells[2].firstChild.nodeValue);
num2=parseInt(num2.cells[2].firstChild.nodeValue);
if(num1>num2){
return -1;
}else if(num1==num2){
return 0;
}else{
return 1;
}
}
jsp页面主体如下
<body>
<%
if(session.getAttribute("itemList")!=null){
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
ArrayList<Item> itemList=(ArrayList<Item>)session.getAttribute("itemList");
%>
<table align="center" border="1" id="itemsTable">
<caption>商品信息</caption>
<thead>
<tr>
<th width="60">编号</th>
<th width="130">名称</th>
<th width="80" style="cursor: pointer;" οnclick="itemSort()">价格</th>
<th>产地</th>
<th width="100">上架时间</th>
</tr>
</thead>
<tbody>
<%
Iterator it=itemList.iterator();
int i=1;
while(it.hasNext()){
Item item=(Item)it.next();
if(i%2==0){
%>
<tr style="background-color: red;">
<%
}else{
%>
<tr style="background-color: green;">
<%
}
%>
<th width="60"><%=item.getId() %></th>
<th width="130"><%=item.getName() %></th>
<th width="80"><%=item.getPrice() %></th>
<th><%=item.getAddress() %></th>
<th width="100"><%=df.format(item.getBorth()) %></th>
</tr>
<%
i++;
}
%>
</tbody>
</table>
<table align="center">
<tr>
<td>
<a href="javascript:goPage('first')">首页</a>
</td>
<td>
<a href="javascript:goPage('back')">上一页</a>
</td>
<td>
<a href="javascript:goPage('next')">下一页</a>
</td>
<td>
<a href="javascript:goPage('last')">末页</a>
</td>
<td><%=currenPage %>(当前页数)/<%=maxPage %>(总页数)</td>
<td>共<%=total %></>行</td>
</tr>
</table>
<%
}
%>
</body>