javascript从html代码计算总数

时间:2011-03-08 15:48:08

标签: javascript

我有

<tr>
<td nowrap="" align="right" id="n_852" class="tab ">1</td>
<td nowrap="" align="right" id="n_853" class="tab ">2</td>
<td nowrap="" align="right" id="n_854" class="tab ">3</td>
<td nowrap="" align="right" id="n_855" class="tab ">4</td>

</tr>

在js中可以遍历数组n_i并计算总1+2+3+4

感谢

2 个答案:

答案 0 :(得分:3)

function doSum()
{
  var stillGoing = true;
  var sum = 0;
  var i = 852;
  while (stillGoing)
  {
    var element = document.getElementById('n_' + i);
    if (element != null)
    {
      sum += parseInt(element.innerHTML);
    }
    else
    {
      stillGoing = false;
    }
    i++;
  }
  return sum;
}

答案 1 :(得分:3)

http://jsfiddle.net/ZBLzp/

您可以将*更改为td

,从而使其更具限制性
var elements=document.getElementsByTagName("*"),
    partial = new RegExp('n_','g'),
    total = 0;

for(var i=0; i< elements.length;i++){
    if(elements[i].id.match(partial)){
        total+= parseInt(elements[i].innerHTML);
    }
}