标签:
获取表格某列所有单元格内容:
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>
标签:
原文地址:http://www.cnblogs.com/sky-zhao/p/5053467.html