2011-09-18 90 views
2

我在我的頁面的正文和頭部都有JS代碼。如果我想讓它們位於外部.js文件中,我將如何移動它們然後將它們回調到頁面上?如何將內聯JS編碼轉換爲外部樣式表?

頭 -

<script language="Javascript"> 
setInterval("settime()", 1000); 

function settime() { 
var curtime = new Date(); 
var curhour = curtime.getHours(); 
var curmin = curtime.getMinutes(); 
var cursec = curtime.getSeconds(); 
var time = ""; 

if(curhour == 0) curhour = 12; 
time = (curhour > 12 ? curhour - 12 : curhour) + ":" + 
    (curmin < 10 ? "0" : "") + curmin + ":" + 
    (cursec < 10 ? "0" : "") + cursec + " " + 
    (curhour > 12 ? "pm" : "am"); 

document.date.clock.value = time; 
} 
</script> 

體 -

<script language="JS" type="text/javascript"> 
var monthArray = new Array("January", "February", "March", "April", "May", 
         "June", "July", "August", "September", 
         "October", "November", "December"); 

var today = new Date(); 
var todayMonth = today.getMonth(); 
var todayDate = today.getDate(); 
var todayYear = today.getFullYear(); 
document.write(monthArray[todayMonth] + " " + todayDate + ", " + todayYear); 
</script> 

回答

2

移動你的JS代碼到外部文件(比如說,my.js)和包括您的頁面中它:

<script type="text/javascript" src="my.js"></script>

當然,上面假設my.js位於同一個文件夾/目錄作爲你的頁面。您需要根據您的JS文件的位置調整src的值。

+0

就外部.js文件而言,是否包含標記之間的所有內容,不包括它們? –

+0

是的,這是正確的。確保你把'head'和'body'部分的所有腳本代碼放在一起,因爲你可能在這兩個部分有一些重疊的JS代碼。 – Saket

+0

也許我應該編輯我的帖子頂部並把代碼放在那裏? –

相關問題