我在 HTML 文件中有一个表格,设置如下(这只是表格的一行)
<tr>
<td class = "numeric">0</td>
<td class = "numeric">2</td>
<td class = "numeric">3</td>
<td class = "numeric">1</td>
<td class = "numeric">4</td>
<td class = "numeric" id="city3"> </td>
</tr>
我需要编写一个脚本来检索表中的数字,以便我可以将它们加起来。可以说我完全不知道如何检索信息。如有任何帮助,我们将不胜感激。
最佳答案
如果您想使用 native JavaScript 实现它 ( http://jsfiddle.net/S4XX2/1/ )
var tds = document.getElementsByClassName('numeric');
var total = 0;
for(var i = 0; i < tds.length; i++) {
var textValue = tds[i].innerHTML;
if(textValue != '') {
total += parseInt(textValue);
}
}
alert(total); // alerts the total sumed up
如果您使用 JQuery ( http://jsfiddle.net/S4XX2/2/ )
var total = 0;
$('td.numeric').each(function() {
var textValue = $(this).text();
if(textValue != '') {
total += parseInt(textValue);
}
});
alert(total); // alerts the total sumed up
关于javascript - 将 HTML 数据导入 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23923326/