简体   繁体   中英

Sorting DOM elements doesn't work in IE 8

I'm trying to sort an array of list elements in IE8 like this:

function comparator(params) {
    var keepSelectedOnTop = params.keepSelectedOnTop;

    return function (a, b) {    // a, b are DOM objects
        a = $(a);  // wrap with jQuery
        b = $(b);

        if (keepSelectedOnTop) {
            if (a.is(".selected") && !b.is(".selected")) {
                return -1;
            } else if (!a.is(".selected") && b.is(".selected")) {
                return 1;
            }
        }

        return a.text().localeCompare(b.text());
    }
}

// ...

var items = $("ul li").detach().toArray();

items.sort(comparator(params));

This works for small lists, but when I have many elements I get an undefined is null or not an object error. When I break on the exception with the debugger b is undefined after the assignment.

Did anyone encounter this before? It works fine in other browsers and it seems perfectly valid JS.

PS the jQuery version is 1.7.2

Why sort?

var items = $("ul li")
items = [].concat(items.filter(".selected").toArray()
                  ,items.filter(":not(.selected)").toArray())

After several trial & error attempts it seems that changing the assignments in the comparator solves the issue, but it doesn't make sense:

function comparator(params) {
    var keepSelectedOnTop = params.keepSelectedOnTop;

    return function (aDom, bDom) {
        var a = $(aDom), b = $(bDom);  // Use different vars for the wrappers

        if (keepSelectedOnTop) {
            if (a.is(".selected") && !b.is(".selected")) {
                return -1;
            } else if (!a.is(".selected") && b.is(".selected")) {
                return 1;
            }
        }

        return a.text().localeCompare(b.text());
    }
}

For some reason the above works, but the initial version where I reassigned different values to the parameters doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM