非匿名函數(shù)
function 名字()
{
...
}
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>非匿名函數(shù)</title>
</head>
<body>
<input id="btn1" type="button" value="按鈕">
<script>
var oBtn=document.getElementById('btn1');
function abc()
{
alert('a');
}
oBtn.onclick=abc;
</script>
</body>
</html>
匿名函數(shù)
oBtn.onclick=function()
{
...
}
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>匿名函數(shù)</title>
</head>
<body>
<input id="btn1" type="button" value="按鈕">
<script>
var oBtn=document.getElementById('btn1');
oBtn.onclick=function()
{
alert('a');
}
</script>
</body>
</html>
上面非匿名函數(shù)與匿名函數(shù)例子中的 <input>標(biāo)簽 與 <script>標(biāo)簽 都必須放在<body> 標(biāo)簽中才有效果。
而一般的話<script>標(biāo)簽一般都是放在<head>標(biāo)簽中,那讓我們來試試:
注:下面代碼是錯誤示范哦
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>匿名函數(shù)</title>
<script>
var oBtn=document.getElementById('btn1');
oBtn.onclick=function()
{
alert('a');
}
</script>
</head>
<body>
<input id="btn1" type="button" value="按鈕">
</body>
</html>
運行出來會發(fā)現(xiàn)Cannot set property 'onclick' of null即無法將屬性“onclick”設(shè)置為空。因為JS特點是讀一行執(zhí)行一行,當(dāng)讀到
oBtn.onclick=function()
{
alert('a');
}
時,下面的代碼就沒加載出來,沒加載出來也就找不到<input>標(biāo)簽里的id="btn1",也就是在給不存在的onclick加點擊事件,所以就有Cannot set property 'onclick' of null即無法將屬性“onclick”設(shè)置為空這個錯誤。
而上面例子中的<script>標(biāo)簽要想放在<head>標(biāo)簽中就需要在<script>標(biāo)簽里加上window.onload(on聯(lián)想到事件,load是加載的意思),window.onload意思就是當(dāng)頁面加載完成時發(fā)生的一個事件,下面試試唄:
非匿名函數(shù):
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>非匿名函數(shù)</title>
<script>
window.onload=function abc()
{
var oBtn=document.getElementById('btn1');
function abc()
{
alert('a');
}
oBtn.onclick=abc;
}
</script>
</head>
<body>
<input id="btn1" type="button" value="按鈕">
</body>
</html>
匿名函數(shù)也如此:
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>匿名函數(shù)</title>
<script>
window.onload=function()
{
var oBtn=document.getElementById('btn1');
oBtn.onclick=function()
{
alert('a');
}
}
</script>
</head>
<body>
<input id="btn1" type="button" value="按鈕">
</body>
</html>