每天CookBook之JavaScript-016

  • 使用querySelectorAll获取元素集并计算总和
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>016</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>
</body>
<script type="text/javascript">
var sum = 0;
var cells = document.querySelectorAll("td + td");
for(var i = 0;i < cells.length; i++){
    sum+=parseFloat(cells[i].firstChild.data);
}
var newRow = document.createElement("tr");
    var firstCell = document.createElement("td");
    var firstCellText = document.createTextNode("Sum:");
    firstCell.appendChild(firstCellText);

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

    document.getElementById('table1').appendChild(newRow);
</script>
</html>
posted @ 2016-07-09 11:12  4Thing  阅读(87)  评论(0编辑  收藏  举报