需要将.innerHTML的结果转换为javascript上的数字 [英] Need to convert result of .innerHTML to number on javascript

查看:95
本文介绍了需要将.innerHTML的结果转换为javascript上的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html,其中包含类似于以下示例的表

I have a html that contains tables like the following example

<td class="topiccell">
    <span class="topicnormal">
        <a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
                 40
        </a>
    </span>
</td>
<td class="topiccell">
   <span class="topicnormal">
       <a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
                 3
        </a>
   </span>
</td>

,我需要使用.innerHTML解析40、3和另外75个数字.然后,我想对所有75个数字求和.我使用了以下

and I need to parse 40, 3 and another 75 numbers using .innerHTML. Then I would like to make a sum of all 75 numbers. I used the following

var valuelements = document.getElementsByClassName("value");
var features = new Array(valuelements.length);
for (var i=0; i<=features.length; i++){ 
  var val = valuelements[i].innerHTML;
  var counter = counter + val;
}
document.write(counter); 

结果为40 3等...尝试了parseIntparseFloat.value,但结果始终是NaN.有什么建议吗?

and the result was like 40 3 etc.... tried parseInt, parseFloat, .value but the result always was NaN. Any suggestions?

推荐答案

您需要使用起始数字初始化counter,否则您将在undefined上执行数学运算.

You need to initialize counter with a starting number, otherwise you're performing math on undefined.

var counter = 0;

然后在循环中,对.innerHTML值使用parseIntparseFloat或直接数字转换.

And then in the loop, use parseInt, parseFloat, or a direct number conversion on the .innerHTML value.

var counter = 0;

for (var i=0; i<features.length; i++){ 
  counter += parseFloat(valuelements[i].innerHTML);
}


在现代浏览器中,您可以执行以下操作:


In a modern browser, you could do this:

var count = [].reduce.call(valueelements, function(c, v) {
    return c + parseFloat(v.innerHTML);
}, 0);

这篇关于需要将.innerHTML的结果转换为javascript上的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆