0

从数据库打印的动态数据/表格。需要获得球队获胜、平局、失败的次数。jQuery 超级新手,不知道从什么开始编码(?!)。我正在考虑首先获取 Chelsea 出现的行,然后比较分数,使用数组存储 W、T、L 并在最后打印结果(?)。

这是表格的样子:

<table>
<tr id="12">
   <td class="238 ekipi_1">Chelsea</td>
   <td class="231 ekipi_2">ManU</td>
   <td class="goals_238">4</td>
   <td class="goals_231">2</td>
</tr>

<tr id="13">
   <td class="242 ekipi_1">Reading</td>
   <td class="238 ekipi_2">Chelsea</td>
   <td class="goals_242">3</td>
   <td class="goals_238">3</td>
</tr>

<tr id="16">
   <td class="251 ekipi_1">Swansea</td>
   <td class="238 ekipi_2">Chelsea</td>
   <td class="goals_251">5</td>
   <td class="goals_238">3</td>
</tr>
</table>

结果将是:

          W   T   L

Chelsea | 1 | 1 | 1 |
Reading | 0 | 1 | 0 |
ManU    | 0 | 0 | 1 |

任何领先的提示将不胜感激。

4

1 回答 1

1

要读取初始数据并构建对象,您可以这样做..

    var teams = {
    "Chelsea": {"W": 0, "T": 0, "L": 0},
    "ManU": {"W": 0, "T": 0, "L": 0},
    "Reading": {"W": 0, "T": 0, "L": 0},
    "Swansea": {"W": 0, "T": 0, "L": 0}
};

$('table tr').each(function() {
    var $this = $(this);
    var team1 = $this.find('td:eq(0)').text();
    var team2 = $this.find('td:eq(1)').text();
    var score1 = $this.find('td:eq(2)').text();
    var score2 = $this.find('td:eq(3)').text();

    if(+score1 === +score2){
        teams[team1]["T"] =  +teams[team1]["T"] +1; 
        teams[team2]["T"] =  +teams[team2]["T"]+1; 
    }  
    else if(+score1 > +score2){
        teams[team1]["W"] =  +teams[team1]["W"]+1; 
        teams[team2]["L"] =  +teams[team2]["L"]+1; 
    }
    else{
        teams[team1]["L"] =  +teams[team1]["L"]+1; 
        teams[team2]["W"] =  +teams[team2]["W"]+1; 
    }        
});

// Print the data

$.each(teams, function(key,value){
    var $clone = $('#template');
    $clone.find('.team').html(key);
    $clone.find('.score:eq(0)').html(value["W"]);
    $clone.find('.score:eq(1)').html(value["T"]);   
    $clone.find('.score:eq(2)').html(value["L"]);
    $('#output').append($clone.html());
});

检查小提琴

完成后,您可以阅读团队对象并打印出来。

于 2012-11-29T23:24:23.433 回答