简体   繁体   中英

sort() function in IE

So this code doesnt seem to work with IE, I have not found anything that says it shouldn't. What am I doing wrong?

 ​<ul id="cars">
    <li id="2">Ford</li>
    <li id="1">Volvo</li>
    <li id="3">Fiat</li>
    </ul>



var list = $('#cars').children('li');
    list.sort(function(a,b){
        return parseInt(a.id) < parseInt(b.id);
    });
    $('#cars').append(list);

The sort function you pass in should return either a number less than zero (a comes before b), 0 (a and b are equivalent) or greater than 0 (a comes after b).

If you just do this, it should work:

return parseInt(a.id) - parseInt(b.id);

also can't hurt to pass in the radix argument to parseInt, it's a bit safer:

return parseInt(a.id, 10) - parseInt(b.id, 10);

It's considered incorrect in HTML4 to start IDs with numbers. This rarely causes problems in browsers, but it's also easily avoided.

I replaced your IDs with data- attributes, which are automatically extracted by the .data() method in jQuery and converted into numbers, eliminating the need for parseInt .

HTML:

<ul id="cars">
    <li data-val="2">Ford</li>
    <li data-val="1">Volvo</li>
    <li data-val="3">Fiat</li>
</ul>

JS:

$('#cars').children('li').sort(function(a, b) {
    return $(a).data('val')-$(b).data('val');
}).appendTo('#cars');​​​​​
​

Fiddle: http://jsfiddle.net/qaytJ/1/

data- attributes are useful whenever you want to attach arbitrary data to HTML elements, and it's more "correct", or at least more appropriate, than forcing id or class to do a job it wasn't intended to do. Use them often.

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