JavaScript学习与实践(5)
条件语句在JS中用于在不同的条件下执行特定的语句块的语句,
下面的例子分别演示如何写一个IF语句,IF...ELSE语句,IF..ELSE IF...ELSE 语句,还有一个随机链接的例子,代码如下
一
<html>
<body>
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("<b>Good morning</b>")
}
</script>
<p>
This example demonstrates the If statement.
</p>
<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
</p>
</body>
</html>
二
<html>
<body>
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("<b>Good morning</b>")
}
else
{
document.write("<b>Good day</b>")
}
</script>
<p>
This example demonstrates the If...Else statement.
</p>
<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.
</p>
</body>
</html>
三
<html>
<body>
<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>
<p>
This example demonstrates the if..else if...else statement.
</p>
</body>
</html>
四
<html>
<body>
<script type="text/javascript">
var r=Math.random()
if (r>0.5)
{
document.write("<a href='http://www.sohu.com'>Learn Web Development!</a>")
}
else
{
document.write("<a href='http://www.163.com'>Visit Refsnes Data!</a>")
}
</script>
</body>
</html>
t条件语句
这个是你写代码使用很频繁的语句,根据不同的条件执行特定的代码,在,JS里,你可以根据需要选择IF ,IF..ELSE,if..else if...else,或者是SWITCH语句,