JavaScript if/else 语句

定义和用法

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 支持 支持 支持 支持 支持

相关页面

JavaScript 教程:JavaScript If...Else 语句

JavaScript 教程:JavaScript Switch 语句


http://www.vxiaotou.com