jquery循环表,同时添加值

时间:2013-12-09 23:19:40

标签: jquery

我有下表由php填充并包含“卡路里”,“蛋白质”,“碳水化合物”和“脂肪”列中的值。我正在尝试编写一个jquery脚本,它将遍历表并总计所有卡路里值,蛋白质值,碳水化合物值和脂肪值。我对jquery很新,所以我有一段艰难的时光。这是结构:

<table id="planner_table" class="display">
          <thead class="planner_table_head">
            <tr>
              <th class="planner_th">Meal Name</td>

              <th class="planner_th">Calories</th>

              <th class="planner_th">Protein</th>

              <th class="planner_th">Carbs</th>

              <th class="planner_th">Fats</th>
            </tr>
          </thead>

          <tbody>
            <?php $dao->fillPlanner($_SESSION['user_id']); ?>
          </tbody>
        </table>

这些是PHP生成的条目:

echo '<tr>';
echo '<td class="centered">' . content . '</td>';
echo '<td class="centered cals">' . content . '</td>';
echo '<td class="centered prot">' . content . '</td>';
echo '<td class="centered carbs">' . content . '</td>';
echo '<td class="centered fats">' . content . '</td>';
echo '</tr>';

任何帮助表示赞赏。感谢

2 个答案:

答案 0 :(得分:1)

要计算卡路里列中的卡路里数,请执行以下操作:

var totalCals = 0;

$('td.cals').each(function(){
    totalCals += parseInt($(this).html(), 10);
});

这假定每个内容中的唯一内容只是要添加的数字。

您也可以对其他列类型执行相同的操作。

答案 1 :(得分:0)

您可以使用jQuery .each()函数迭代dom元素,这里是<tr>。 所以基本上,这是一种方法(我没有完全写它,所以你将自己完成):

$('#planner_table tr').each(function(i) {
    var cals = $('td.cals', this);
    var prot = $('td.prot', this);
    var carbs = $('td.carbs', this);
    var fats = $('td.fats', this);
});