当前位置:编程学习 > JS >>

JavaScript If...Else 入门实例教程

JavaScript If...Else 入门实例教程

有条件的声明在JavaScript被用来执行不同的行动,根据不同的条件。

条件语句
往往当你写代码,您要执行不同的行动不同的决定。您可以使用条件语句中的代码来做到这一点。

在JavaScript中,我们有以下条件语句:

如果声明-使用此声明如果你想执行一些代码只有在指定的条件是真的
如果... else语句-使用此声明如果你想执行一些代码,如果条件是真实的,如果另一代码的条件是假的
如果别人...如果.... else语句-使用此声明如果你想选择一个许多区块的代码将被处决
switch语句-使用此声明如果你想选择一个许多区块的代码将被处决


如果声明
您应该使用if语句如果你想执行一些代码只有在指定的条件是真实的。

语法

if (condition)
{
code to be executed if condition is true
}
请注意,如果是写字母。用大写字母( IF )的会产生一个JavaScript错误! 范例1<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10var d=new Date();
var time=d.getHours();

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>if... else语句如果你想执行一些代码,如果一个条件是真实的,如果另一代码的条件是不正确的,如果使用.... else语句。 语法if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}实例.script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.var d = new Date();
var time = d.getHours();

if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>If...else if...else Statement您应该使用的,如果....如果别人... else语句如果你想选择一个多台线执行。 语法if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,