示例效果:
JS代码:
// Create variables for the welcome message
var greeting = '您好, ';
var name = '黄先生';
var message = ',您的结账单如下:';
// Concatenate the three variables above to create the welcome message
var welcome = greeting + name + message;
// Create variables to hold details about the sign
var sign = '希尔顿大酒店';
var tiles = sign.length;
var subTotal = tiles * 5;
var shipping = 7;
var grandTotal = subTotal + shipping;
// Get the element that has an id of greeting
var el = document.getElementById('greeting');
// Replace the content of that element with the personalized welcome message
el.textContent = welcome;
// Get the element that has an id of userSign then update its contents
var elSign = document.getElementById('userSign');
elSign.textContent = sign;
// Get the element that has an id of tiles then update its contents
var elTiles = document.getElementById('tiles');
elTiles.textContent = tiles;
// Get the element that has an id of subTotal then update its contents
var elSubTotal = document.getElementById('subTotal');
elSubTotal.textContent = '$' + subTotal;
// Get the element that has an id of shipping then update its contents
var elShipping = document.getElementById('shipping');
elShipping.textContent = '$' + shipping;
// Get the element that has an id of grandTotal then update its contents
var elGrandTotal = document.getElementById('grandTotal');
elGrandTotal.textContent = '$' + grandTotal;
/*
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML instead of textContent, but note the security issues on p228-231
In the first print run, line 33-34 repeated elSubTotal (rather than elShipping).
This was fixed in later print runs and in this code sample.
*/
HTML代码:
<html>
<head>
<meta content="text/html; charset=utf-8"/>
<title>JavaScript & jQuery - Chapter 2: Basic JavaScript Instructions - Example</title>
<link rel="stylesheet" href="css/c02.css" />
</head>
<body>
<h1>Elderflower</h1>
<div id="content">
<div id="greeting" class="message">Hello!</div>
<table>
<tr>
<td>Custom sign: </td>
<td id="userSign"></td>
</tr>
<tr>
<td>Total tiles: </td>
<td id="tiles"></td>
</tr>
<tr>
<td>Subtotal: </td>
<td id="subTotal">$</td>
</tr>
<tr>
<td>Shipping: </td>
<td id="shipping">$</td>
</tr>
<tr>
<td>Grand total: </td>
<td id="grandTotal">$</td></tr>
</table>
<a href="#" class="action">Pay Now</a>
</div>
<script src="js/example.js"></script>
</body>
</html>
CSS代码:(参考:源码-JavaScript&jQuery交互式前端开发-第2章-JavaScript基础指令-使用变量来存储数字,http://blog.csdn.net/hpdlzu80100/article/details/52669264)