一 頁面輸出
1.頭部檔案
複製代碼 代碼如下:<head>
<script language="javascript">
document.write("指令碼之家www.jb51.net");
</script>
</head>
2.頁面內 複製代碼 代碼如下:<body>
<script>
document.write("指令碼之家");
</script>
</body>
3.外部檔案
<script src="display.js"></script>
4.利用頁面ID的innerHtml 複製代碼 代碼如下:<script>
window.onload = writeMessage; // 頁面載入時調用writeMessage函數
writeMessage() {
document.getElementById("helloMessage").innerHTML = "指令碼之家";
//找到dom ID(helloMessage),修改其html內容
}
</script>
5.警告
alert("廣州百匯物流有限公司");
6.詢問 複製代碼 代碼如下:if (confirm("是否訪問我們的首頁"))
{
alert("是的,前往");
}
else {
alert("退出");
}
7.輸入 複製代碼 代碼如下:var ans = prompt("輸入你的留言","您好,");
if (ans) {
alert("你說:" + ans);
}
else {
alert("退出,沒有留言");
}
8.頁面跳轉 複製代碼 代碼如下:<script>
window.onload = initAll;
function initAll() {
document.getElementById("redirect").onclick = initRedirect;
}
function initRedirect()
{
window.location = "index.html";
return false;
}
</script>
<a href="http://www.jb51.net" id="redirect">指令碼之家</a>
9.判斷分支 複製代碼 代碼如下:<script>
window.onload = initAll;
function initAll() {
document.getElementById("Lincoln").onclick = saySomething;
document.getElementById("Kennedy").onclick = saySomething;
document.getElementById("Nixon").onclick = saySomething;
}
function saySomething() {
switch(this.id) {
case "Lincoln":
alert("Four score and seven years ago...");
break;
case "Kennedy":
alert("Ask not what your country can do for you...");
break;
case "Nixon":
alert("I am not a crook!");
break;
default:
}
}
</script>
<form action="#">
<input type="button" id="Lincoln" value="Lincoln" />
<input
type="button" id="Kennedy" value="Kennedy" />
<input type="button" id="Nixon"
value="Nixon" />
</form>
10.異常捕獲 複製代碼 代碼如下:window.onload = initAll;
function initAll() {
var ans = prompt("輸入參數:","");
try {
if (!ans || isNaN(ans) || ans<0) {
throw new Error("輸入為非數");
}
alert("根號" + ans + " 是 " + Math.sqrt(ans));
}
catch (errMsg) {
alert(errMsg.message);
}
}