用script标记导入外部脚本文件,最好是将脚本文件放在整个html文件的最下方。若js文件放在需要控制元素的前面会导致dom对象无法读取html元素。浏览器会出现js文件解析错误的bug。
如:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="Description" content=""/>
<meta name="Keywords" content="" />
<title>无标题文档</title>
</head>
<link rel="stylesheet" href="css/stylesheet.css" type="text/css"/>
<body>
<span id="Subtotal"></span>
<img class="headImg" src="images/elderflower-logo.png" alt="图片加载失败"/>
<script src="javascripts/action.js"></script>
<div>
<table>
<caption>Howdy Molly, please check your order:</caption>
<tr>
<th>Custom sign:</th>
<td id="customSign">hello</td>
</tr>
<tr>
<th>Total tiles: </th>
<td id="totalTiles">22</td>
</tr>
<tr>
<th>Subtotal:</th>
<td ></td>
</tr>
<tr>
<th>Shipping:</th>
<td id="shipping"></td>
</tr>
<tr>
<th>Grand total:</th>
<td id="grandTotal"></td>
</tr>
</table>
<a class="payNow" href="#">PAY Now</a>
</div>
</body>
</html>
引入的js:
// JavaScript Document
var totalTiles= 14;
var TilePrice = 5;
var subtotal = totalTiles * TilePrice;
var shipping = 7 ;
/*if(document.getElementById('Subtotal')!=null){
alert('可以获取');
}
else{
alert('没有获取到对象');
}*/
/*var x = document.getElementById('Subtotal');
x.textContent = subtotal;*/
function CustomSign(){
'use strict';
var customSign = 'Montague House';
var get = document.getElementById('customSign');
get.textContent=customSign;
}
function showTotal(){
'use strict';
var x ;
x=document.getElementById('totalTiles');
x.textContent = totalTiles;
}
function showSub(){
'use strict';
var x = document.getElementById('Subtotal');
x.textContent = subtotal;
}
function showShip(){
'use strict';
var x = document.getElementById('shipping');
x.textContent = shipping;
}
function showGrand(){
'use strict';
var grandTotal = subtotal + shipping;
var x = document.getElementById('grandTotal');
x.textContent = grandTotal;
}
CustomSign();
showTotal();
showSub();
showShip();
showGrand();
结果是函数内用于控制html元素的代码块获取 不到对象,导致变量的值为null。
将script标签放在table标签后面不会出现此问题