JavaScript-6 For…..in 、Try…..catch、特殊字符
For in 聲明:對數組或對象的屬性進行循環操作。
for(變量 in 對象)
{
帶碼
}
例一:
<html>
<body>
<script type="text/javascript">
var x
var num = new Array()
num[0] = "1"
num[1] = "2"
num[2] = "3"
for (x in num)
{
document.write(num[x] + " ")
}
</script>
</body>
</html>
運行結果:1 2 3
事件:事件通常與函數配合使用,當事件發生時函數執行。
事件:onMouseOver onMouseOut onclick onSubmit
例一:
<input type="button" value="點擊改變" onclick="f1()">
關於事件應用請參考3消息框中的簡介。
Try…catch語句:
Try{
運行代碼
}catch(err){
處理錯誤
}
例一:
<html>
<head>
<script type="text/javascript">
function f1()
{
try
{
allllert("Hello!")
}
catch(err)
{
alert("heihei")
}
}
</script>
</head>
<body>
<input type="button" value="View message" />
</body>
</html>
Try中alert錯寫爲allller,所以執行catch中的alert。
例二:帶確認框的
<html>
<head>
<script type="text/javascript">
var txt=""
function message(){
try {
adddlert("Welcome guest!")
}
catch(err) {
txt="本頁中存在錯誤。\n\n"
txt+="點擊“確定”繼續查看本頁,\n"
txt+="點擊“取消”返回首頁。\n\n"
if(!confirm(txt)){
document.location.href="/index.html"
}
}
}
</script>
</head>
<body>
<input type="button" value="查看消息" />
</body>
</html>
特殊字符:我們需要插入一些特殊字符的時候並不能直接輸入這些特殊字符。比如省略號、引號、和其他字符。我們需要使用反斜槓。
\’表示單引號 \”表示雙引號 \&表示and符號 \\表示反斜槓 \n表示換行 \r表示回車 \t表示製表符 \b表示退格符 \f表示換行符 \表示後面的代碼可以寫在下一行中,但在頁面中和前一行代碼顯示在同一行。
例一:舉例:\
document.write("Hello \
World!")
雖然不在同一行,但是因爲有\可以讓代碼折行,所以在頁面中Hello World也是在同一行顯示。