1

我正在尝试对表格进行排序。我见过几个 jQuery 和 JavaScript 解决方案,它们通过各种方式做到这一点,但是,还没有看到任何使用 JavaScript 的本机 sort() 方法的解决方案。也许我错了,但在我看来,使用 sort() 会更快。

以下是我的尝试,但是,我肯定遗漏了一些东西。我正在尝试做的事情是否可行,或者我应该放弃它吗?理想情况下,我想远离 innerHTML 和 jQuery。谢谢

var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;

//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
    b[i] = a[i];
}

var x_td, y_td;

b.sort(function(x, y) {
    //Having to use getElementsByTagName is probably wrong
    x_td = x.getElementsByTagName('td')[index].data;
    y_td = y.getElementsByTagName('td')[index].data;
    return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
4

2 回答 2

1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>All Sorting Techniques</title>
        <script type="text/javascript">

var a = [21,5,7,318,3,4,9,1,34,67,33,109,23,156,283];
function bubbleSort(a)
{
    var change;
    do {
        change = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                change = true;
            }
        } 
    } while (change);
    document.getElementById("bublsrt").innerHTML = "Bubble Sort Result is:  "+a;
}
var b = [1,3,4,5,7,9,21,23,33,34,67,109,156,283,318];
function binarySearch(b, elem){
    var left = 0;
    var right = b.length - 1;
    while (left <= right){
    var mid = parseInt((left + right)/2);
    if (b[mid] == elem)
    return mid;
    else if (b[mid] < elem)
    left = mid + 1;
    else
    right = mid - 1;
    }
    return b.length;
}
function searchbinary(){
    var x = document.getElementById("binarysearchtb").value;
    var element= binarySearch(b,x);
    if(element==b.length)
    {
        alert("no. not found");
    }
    else
    {
        alert("Element is at the index number: "+ element);     
    }
}
function quicksort(a)
{
    if (a.length == 0)
        return [];
    var left = new Array();
    var right = new Array();
    var pivot = a[0];
     for (var i = 1; i < a.length; i++) {
        if (a[i] < pivot) {
           left.push(a[i]);
        } else {
           right.push(a[i]);
        }
    }
    return quicksort(left).concat(pivot, quicksort(right));
}
function quicksortresult()
{
    quicksort(a);
    document.getElementById("qcksrt").innerHTML = "Quick Sort Result is:  "+quicksort(a);
}
function numeric(evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) 
            theEvent.preventDefault();
    }
}
function insertionsorting(a)
{
    var len = a.length;     
    var temp;                     
    var i;
    var j;
        for (i=0; i < len; i++) {
        temp = a[i];
        for (j=i-1; j > -1 && a[j] > temp; j--) {
            a[j+1] = a[j];
        }
        a[j+1] = temp;
    }
    document.getElementById("insrtsrt").innerHTML = "Insertion Sort Result is:  "+a;
}
function hiddendiv()
{
    document.getElementById("binarytbdiv").style.display = "none";
    document.getElementById("Insertnotbdiv").style.display = "none";
}
function binarydivshow()
{
    document.getElementById("binarytbdiv").style.display = "block";
}
function insertnodivshow()
{
    document.getElementById("Insertnotbdiv").style.display = "block";
}
function insertno(a)
{
    var extrano = document.getElementById("Insertnotb").value;
    var b= a.push(extrano);
    var change;
    do {
        change = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                change = true;
            }
        }
    } while (change);
    document.getElementById("insrtnosearch").innerHTML = "Sorted List is:  "+a;
    alert("Index of "+extrano +" is " +a.indexOf(extrano));
}


</script>
    </head>
    <body onload="hiddendiv()">
        <h1 align="center">All Type Of Sorting</h1>
        <p align="center">Your Array is : 21,5,7,318,3,4,9,1,34,67,33,109,23,156,283</p>
        <div id="main_div" align="center">
            <div id="bubblesort">
                <input type="button" id="bubblesortbutton" onclick="bubbleSort(a)" value="Bubble Sort">
                <p id="bublsrt"></p>
            </div><br>
            <div id="quicksort">
                <input type="button" id="quicksortbutton" onclick="quicksortresult()" value="Quick Sort">
                <p id="qcksrt"></p>
            </div><br>
            <div id="insertionsort">
                <input type="button" id="insertionsortbutton" onclick="insertionsorting(a)" value="Insertion Sort">
                <p id="insrtsrt"></p>
            </div><br>
            <div id="binarysearch">
                <input type="button" id="binarysearchbutton" onclick="binarydivshow();" value="Binary Search">
                <div id="binarytbdiv">
                    <input type="text" id="binarysearchtb" placeholder="Enter a Number" onkeypress="numeric(event)"><br>
                    <input type="button" id="binarysearchtbbutton" value="Submit" onclick="searchbinary()">
                    <p id="binarysrch">Sorted List is : 1,3,4,5,7,9,21,23,33,34,67,109,156,283,318</p>
                </div>
            </div><br>
            <div id="Insertno">
                <input type="button" id="insertno" onclick="insertnodivshow()" value="Insert A Number">
                <div id="Insertnotbdiv">
                    <input type="text" id="Insertnotb" placeholder="Enter a Number" onkeypress="numeric(event);"><br>
                    <input type="button" id="Insertnotbbutton" value="Submit" onclick="insertno(a)">
                    <p id="insrtnosearch"></p>
                </div>
            </div>
        </div>
    </body>
</html>
于 2013-04-16T11:25:22.473 回答
1

td元素没有属性.data

如果您想要元素的文本内容,并且只有一个文本节点,请使用.firstChildbefore .data

然后,完成后,您需要将元素附加到 DOM。对 JavaScript 元素数组进行排序对 DOM 没有任何影响。

此外,getElementsByTagName("td")您可以只使用.cells.

b.sort(function(rowx, rowy) {
    x_td = rowx.cells[index].firstChild.data;
    y_td = rowy.cells[index].firstChild.data;
    return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});

var parent = b[0].parentNode;

b.forEach(function(row) {
    parent.appendChild(row);
});

如果您要比较的内容是数字,则应将字符串转换为数字。

如果它们是文本字符串,那么您应该使用.localeCompare().

return x_td.localeCompare(y_td);
于 2012-11-13T23:32:32.140 回答