JavaScript 10.29
阿新 • • 發佈:2021-10-29
1.1函式的概述
我們現在的電腦科學 還沒有脫離數學的範疇。 是應用數學的另一種表現形式。 計算中很多的術語都源於數學。所以 函式這個名詞其實也是源於數學。
我們之前學過很多語句,例如
if(){} 條件語句 , 控制大括號程式碼塊 是否執行。
for(){} 迴圈語句, 控制大括號程式碼塊 執行多少次。
function(){} 函式,控制大括號程式碼塊 何時執行。 函式實在呼叫的時候才會去執行。
1.2 函式的宣告和呼叫
函式宣告:
function 名字(){
程式碼塊
}
函式呼叫:
函式名();
<script type="text/javascript">
/* 函式宣告之後 程式碼是不執行的 */
function haha(){
document.write("123");
document.write("123");
document.write("123");
}
/* 只有呼叫函式的時候 才會去執行 並且呼叫多少次 就 執行多少次 */
haha();
haha();
haha();
</script>
1.3 函式事件繫結
點選頁面按鈕 改變背景顏色
<body>
<button onclick="haha()">改變</button>
<!-- ---------------------------------------------------------------------------------------------------- -->
<script type="text/javascript">
/* who button when onclick what 改變背景顏色 */
function haha(){
document.body.style.backgroundColor = "red";
}
</script>
</body>
點選按鈕改變圖片:
<button onclick="haha1()">紅</button>
<button onclick="haha2()">黃</button>
<button onclick="haha3()">藍</button>
<button onclick="haha4()">綠</button>
<img id="foo" src="" width="200" height="200">
<!-- ---------------------------------------------------------------------------------------------------- -->
<script type="text/javascript">
function haha1(){
foo.src = "img/d_1.png";
}
function haha2(){
foo.src = "img/d_2.png";
foo.style.width = "800px";
}
function haha3(){
foo.src = "img/d_3.png";
}
function haha4(){