现在位置: 首页 > JavaScript 参考手册 > 正文

JavaScript if/else 语句

JavaScript 语句参考手册 JavaScript 语句参考手册

实例

如果当前时间(小时)小于 20:00, 在 id="demo" 元素上输出 "Good day" :

var time = new Date().getHours();
if (time < 20) {
    document.getElementById("demo").innerHTML = "Good day";
}

输出结果:


尝试一下 »

本文底部包含更多实例。


定义和用法

if/else 语句在指定的条件为 true 时,执行代码块。如果条件为 false,会执行另外一个代码块。

if/else 语句是 JavaScript 条件语句的一部分, 条件语句用于基于不同的条件来执行不同的动作。

在 JavaScript 中,我们可使用以下条件语句:

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码。
  • else 语句 如果 if 语句的条件为false,则执行该代码块
  • else if 语句 - 检测一个新的条件,如果第一个条件为false
  • switch 语句 - 选择多个代码块中其中一个执行

浏览器支持

语句
if/else Yes Yes Yes Yes Yes


语法

if 语句指定了在条件为 true 时执行的代码块:

if (condition) {
    如果 condition 为 true 执行该代码块
}

else 语句指定在条件为 false 时执行的代码块:

if (condition) {
    如果 condition 为 true 执行该代码块
} else {
    如果 condition 为 false 执行该代码块
}

else if 语句在第一个条件为false时指定了新的条件:

if (condition1) {
    如果 condition1 为 true 执行该代码块
} else if (condition2) {
    如果 condition1 为 false 且 condition2 为 true 执行该代码块
} else {
    如果 condition1 为 false 且 condition2 为 false 执行该代码块
}

参数值

参数 描述
condition 必须。表达式,用于条件判断: true 或 false

技术细节

JavaScript 版本: 1.0


实例

更多实例

实例

如果时间小于 20:00, 生成一个 "Good day" 问候,否则输出 "Good evening":

var time = new Date().getHours();
if (time < 20) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}

问候语的输出结果为:

var d=new Date(); var time=d.getHours(); if (time<20) { document.write("Good day"); } else { document.write("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";
}

问候语输出结果为:

var d=new Date(); var time=d.getHours(); if (time<10) { document.write("Good morning"); } else if (time<20) { document.write("Good day"); } else { document.write("Good evening"); }

尝试一下 »

实例

修改文档中第一个 id 等于 "myDIV" 的 <div> 元素的字体号:

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 x, text;

// 获取 id="numb" 输入框的值

x = document.getElementById("numb").value;

// 如果 x 不是换一个数字或 x 小于 1 或大于10 输出 "请输入合法值"
// 如果 x 的值介于 1 和 10 之间,输出 "输入正确"

if (isNaN(x) || x < 1 || x > 10) {
    text = "请输入合法值";
} else {
    text = "输入正确";
}
document.getElementById("demo").innerHTML = text;

尝试一下 »


相关页面

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

JavaScript 教程: JavaScript Switch 语句


JavaScript 语句参考手册 JavaScript 语句参考手册