jQuery - 板球计算

时间:2015-02-11 04:58:27

标签: jquery jquery-calculation

有人可以帮我解决下面的jQuery吗?

我想根据比赛1和比赛2信息自动添加玩家的运行,SR等...

HTML

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <th>Name</th>
    <th>Total Runs</th>
    <th>Total Balls</th>
    <th>Match 1 Runs</th>
    <th>Match 1 Balls</th>
    <th>Match 2 Runs</th>
    <th>Match 2 Balls</th>
    <th>Strite Rate</th>
  </tr>
  <tr>
    <td>Player 1</td>
    <td>Total Runs: <span class="player-stat-runs"></span></td>
    <td>Total Balls: <span class="player-stat-balls"></span></td>
    <td>15</td>
    <td>16</td>
    <td>20</td>
    <td>14</td>
    <td><span class="player-stat-avg"></span></td>
  </tr>
  <tr>
    <td>Player 2</td>
    <td>Total Runs: <span class="player-stat-runs"></span></td>
    <td>Total Balls: <span class="player-stat-balls"></span></td>
    <td>3</td>
    <td>4</td>
    <td>68</td>
    <td>94</td>
    <td><span class="player-stat-avg"></span></td>
  </tr>
</table>

CSS

table,th,td{border:1px solid #222;border-collapse:collapse;max-width:500px;}th{font-weight:bold;background:#efefef;}th,td{padding:5px;}
  1. 玩家总跑(比赛1比赛+比赛2比赛)
  2. 球员的总球数(比赛1球+比赛2球)
  3. 击球手打击率(PS:如果击球手从10个球中得到10分SR = 100.00)
  4. Fiddle

1 个答案:

答案 0 :(得分:1)

您可以为运行和球class添加td属性,以便您可以轻松找出td s进行计算。见下表

<table class="table table-bordered">
  <tr>
    <th>Name</th>
    <th>Total Runs</th>
    <th>Total Balls</th>
    <th>M1 Runs</th>
    <th>M1 Balls</th>
    <th>M2 Runs</th>
    <th>M2 Balls</th>
    <th>Strite Rate</th>
  </tr>
<tbody>
  <tr>
    <td>Player 1</td>
    <td class="totalRuns">Total Runs: <span class="player-stat-runs"></span></td>
    <td class="totalBalls">Total Balls: <span class="player-stat-balls"></span></td>
    <td class="runs">15</td>
    <td class="balls">16</td>
    <td class="runs">20</td>
    <td class="balls">14</td>
    <td class="strikeRate"><span class="player-stat-avg"></span></td>
  </tr>
  <tr>
    <td>Player 2</td>
    <td class="totalRuns">Runs: <span class="player-stat-runs"></span></td>
    <td class="totalBalls">Balls: <span class="player-stat-balls"></span></td>
    <td class="runs">3</td>
    <td class="balls">4</td>
    <td class="runs">68</td>
    <td class="balls">94</td>
    <td class="strikeRate"><span class="player-stat-avg"></span></td>
  </tr>
    </tbody>
</table>

现在,使用jQuery下面来计算总跑数,球数和打击率

$(function(){
    $('table.table.table-bordered tbody tr').each(function(){
       var totalRuns = 0;
       var totalBalls = 0;
        $(this).find('.runs').each(function(){
        totalRuns += parseInt($(this).text());
        });

        $(this).find('.balls').each(function(){
        totalBalls += parseInt($(this).text());
        });

       $(this).find('.totalRuns .player-stat-runs').text(totalRuns); 
       $(this).find('.totalBalls .player-stat-balls').text(totalBalls);
       $(this).find('.strikeRate .player-stat-avg').text(parseInt(totalRuns/totalBalls*100)); 

    });
});

<强> JSFiddle Demo