JavaScript if/else 語句
- 上一頁 function
- 下一頁 let
- 返回上一層 JavaScript 語句參考手冊
定義和用法
if/else 語句在指定條件為真時執行代碼塊。如果條件為假,則可以執行另一代碼塊。
if/else 語句是 JavaScript 的“條件”語句的一部分,用于根據不同的條件執行不同的操作。
在 JavaScript 中,我們有以下條件語句:
- 使用 if 指定要執行的代碼塊,如果指定條件為真
- 使用 else 指定要執行的代碼塊,如果相同條件為假
- 如果第一個條件為假,則使用 else if 指定要測試的新條件
- 使用 switch 選擇要執行的多個代碼塊之一
實例
如果當前時間 (HOUR) 小于 20:00,則在 id="demo" 的元素中輸出 "Good day":
var time = new Date().getHours(); if (time < 20) { document.getElementById("demo").innerHTML = "Good day"; }
頁面下方有更多 TIY 實例。
語法
if 語句指定在條件為真時要執行的代碼塊:
if (condition) { // block of code to be executed if the condition is true }
else 語句指定在條件為假時要執行的代碼塊:
if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }
如果第一個條件為假,則 else if 語句指定一個新條件:
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }
參數值
參數 | 描述 |
---|---|
condition | 必需。計算結果為 true 或 false 的表達式。 |
技術細節
JavaScript 版本: | ECMAScript 1 |
---|
更多實例
實例
如果時間小于 20:00,則創建 "Good day" 問候語,否則創建 "Good evening":
var time = new Date().getHours(); if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
實例
如果時間小于 10:00,創建一條 "Good morning" 問候,如果不是,但時間小于 20:00,創建一條 "Good day" 問候語,否則創建一條 "Good evening":
var time = new Date().getHours(); if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
實例
如果文檔中的第一個 <div> 元素的 id 為 "myDIV",則更改其字體大小:
var x = document.getElementsByTagName("DIV")[0]; if (x.id === "myDIV") { x.style.fontSize = "30px"; }
實例
當用戶單擊圖像,更改 <img> 元素的源屬性 (src) 的值:
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180"> <script> function changeImage() { var image = document.getElementById("myImage"); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; } } </script>
實例
根據用戶輸入顯示消息:
var letter = document.getElementById("myInput").value; var text; // 如果字母為 "c" if (letter === "c") { text = "Spot on! Good job!"; // 如果字母為 "b" 或 "d" } else if (letter === "b" || letter === "d") { text = "Close, but not close enough."; // 如果是其他字母 } else { text = "Waaay off.."; }
實例
驗證輸入數據:
var x, text; // 獲取 id="numb" 的輸入字段的值 x = document.getElementById("numb").value; // 如果 x 不是數字或小于 1 或大于 10,則輸出 "input is not valid" // 如果 x 是 1 到 10 之間的數字,則輸出 "Input OK" if (isNaN(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; }
瀏覽器支持
語句 | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
if/else | 支持 | 支持 | 支持 | 支持 | 支持 |
- 上一頁 function
- 下一頁 let
- 返回上一層 JavaScript 語句參考手冊