开发者

How to print the position of each value in a table column using jQuery

Quick jQuery question. Columns in my table represent a racers split time in a race. I want to compare the split time of one racer to the split time of another. For example, I have 3 racers with split times of 3 seconds, 4 seconds and 2 seconds respectively.

In the table cell next to each time, I'd like to output the position compared to other racers like so: 3 s开发者_如何学运维econds (2), 4 seconds (3), and 2 seconds (1).

I'm sure it is a simple matter of adding each split time to an array, then iterating over each and printing the position. However I can't seem to wrap my head around how to accomplish this problem.

Here's a jsfiddle table as an example: http://jsfiddle.net/hYvdp/


If you have this html:

<table cellspacing='5' border=1>
    <tr>
        <td>Race 1 time</td>
        <td>Race 2 time</td>
        <td>Race 3 time</td>
    </tr>
        <tr id='time'>
        <td>4</td>
        <td>1</td>
        <td>2</td>
    </tr>
        <tr id='position'>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

you could do something like this to calculate position:

var racers= []
$('#time td').each(function(){
    var racer = {};
    racer['idx'] = $(this).index();
    racer['time'] =   $(this).text();
    racers.push(racer);
 });
racers.sort(function(a,b){
    if(a.time > b.time){
        return 1;
    }else if(a.time < b.time){
        return -1;
    }
    return 0;
});

var position = 1;
for (i =0; i<racers.length; i++){
    var idx = racers[i].idx;
    $('#position td:eq('+idx+')').html('Position :'+position);
    position++;
}

fiddle here: http://jsfiddle.net/XcpNw/

The third rows has the position that is calculate dinamically: you could attach the same behaviour to a function or to the response of an ajax call

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜