码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript笔记一统计表格数据

时间:2015-12-17 13:00:13      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

获取表格某列所有单元格内容:

querySelectorAll:

字符串转换浮点数:

parseFloat;

创建表元素:

createElement;

创建文本节点:

createTextNode

添加子节点:

appendChild

 

 

var cells = doucment.querySelectorAll("td:nth-of-type(2)"):

for (var i=0; i<cells.length; i++) {

  sum+=parseFloat(cells[i].firstChild.data);

}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Accessing numbers in table</title>
</head>
<body>
<table id="table1">
<tr>
<td>Washington</td>
<td>145</td>
</tr>
<tr>
<td>Oregon</td>
<td>233</td>
</tr>
<tr>
<td>Missouri</td>
<td>833</td>
</tr>
</table>

<script type="text/javascript">
var sum = 0;

//use querySelector to find all second table celss
var cells = document.querySelectorAll("td + td");

for (var i=0; i<cells.length; i++)
sum += parseFloat(cells[i].firstChild.data);

// add sum to end of table;
var newRow = document.createElement("tr");

// first cell
var firstCell = document.createElement("td");
var firstCellText = document.createTextNode("Sum:");
firstCell.appendChild(firstCellText);
newRow.appendChild(firstCell);

//Second cell
var secondCell = document.createElement("td");
var secondCellText = document.createTextNode(sum);
secondCell.appendChild(secondCellText);
newRow.appendChild(secondCell);

//add row to table
document.getElementById("table1").appendChild(newRow);
</script>
</body>
</html>

JavaScript笔记一统计表格数据

标签:

原文地址:http://www.cnblogs.com/sky-zhao/p/5053467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!