需要根据属性值对表进行排序
Need to sort a table based on attribute value
我有一个包含多个值的表,表值从一个表移动到另一个表。当它返回到初始表时,我需要根据字母顺序对这个表进行排序。
我正在使用这个代码,但它不适合我:
var aa = $("#unSelectedTab").find('td');
var abc = '';
for (var i = 0; i < aa.length; i++) {
abc += aa[i].attr("id");
}
虽然代码太多了,但是应该可以了:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.0.js"></script>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
</head>
<body>
<table>
<tbody>
<tr><th>number</th><th>letter</th></tr>
<tr>
<td>3</td>
<td>a</td>
</tr>
<tr>
<td>2</td>
<td>c</td>
</tr>
<tr>
<td>2</td>
<td>c</td>
</tr>
<tr>
<td>2</td>
<td>b</td>
</tr>
<tr>
<td>3</td>
<td>b</td>
</tr>
<tr>
<td>1</td>
<td>c</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function helper_getText(el){
return (el.innerText)?el.innerText:el.textContent;
}
function sortTable(table,byCols){
var rows=table.getElementsByTagName("tr"),
rowArr=[],
i,rowValues=[],j,cells,
tbody=table.getElementsByTagName("tbody")[0];
for(i=0;i<rows.length;i++){
cells=rows[i].getElementsByTagName("td");
if(cells.length===0){
continue;
}else{
rowArr.push($.clone(rows[i]));
rows[i].parentElement.removeChild(rows[i]);
i--;
}
rowValues.push({vals:[],index:rowValues.length});
for(j=0;j<byCols.length;j++){
rowValues[rowValues.length-1].vals.push(
// here you can get the attribute instead
// if there are multiple attributes per column
// to sort on then this gets more difficult
// $.trim(cells[byCols[j]].document.body.getAttribute("data-something"))
$.trim(helper_getText(cells[byCols[j]]))
);
}
}
//sort by multiple columns should be seporate function
rowValues.sort(function(a,b){
var i = 0;
while(a.vals[i]==b.vals[i]&&i<a.vals.length){
i++;
}
if(i===a.vals.length){return 0};
return (a.vals[i]>b.vals[i])?1:-1;
});
//add the rows in the right order
for(i=0;i<rowValues.length;i++){
tbody.appendChild(rowArr[rowValues[i].index]);
}
}
//[1,0] means sort by colum 2 first than by colum 1
sortTable(document.getElementsByTagName("table")[0],[1,0]);
</script>
</body>
</html>
相关文章:
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- row.entity.xxxx属性doensn'排序后不匹配
- 按子属性(可能缺少)对对象的 javascript 数组进行排序
- 按多个属性对多维数组进行排序
- jQuery TinySort按数据属性排序和放置
- AngularJS使用对象属性排序多个对象数组
- 按属性对数组排序
- 如何使用第二个数组中对象的相关属性对对象数组进行排序
- 按属性对对象数组进行排序
- jQueryUI可拖动+可排序错误(无法读取未定义的属性'选项')
- Javascript:使用value属性对关联数组进行排序,而不转换为对象数组
- 为未排序列表设置onclick()属性
- 根据三个模型属性对主干集合进行排序
- 无法读取属性“”;匹配“;(嵌套排序)
- 排序属性由于某种原因不起作用
- 设置排序属性时无法清除数组控制器
- MongoDB多个排序属性:如何确定优先级
- 获取HTML而不重新排序属性
- 用不同的模型排序'属性烬
- 如果Dgrid的id以数字开头,则Dgrid列调整大小,隐藏,重新排序属性会产生错误