2

我有一个包含多个值的表,并且表值从一个表移动到另一个表。当它返回到初始表时,我需要根据字母顺序对该表进行排序。

我正在使用此代码,但它对我不起作用:

    var aa = $("#unSelectedTab").find('td');
    var abc = '';
    for (var i = 0; i < aa.length; i++) {
        abc += aa[i].attr("id");
    }
4

1 回答 1

0

这是很多代码,但应该这样做:

<!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>
于 2013-05-17T08:07:40.340 回答