JavaScript Tutorial/Statement/If — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:25, 26 мая 2010

Conditionals

The format of a simple if statement looks like the following:



if (expression)
      statement;


if...else

Syntax



if(statement){
      code;
    }else(statement){
      code;
    }


if...then...else...if

<html>
<head>
<title>if...then...else...if</title>
<script type="text/javascript">
var stateCode = "MO";
if (stateCode == "OR") {
   taxPercentage = 3.5;
} else if (stateCode == "CA") {
   taxPercentage = 5.0;
} else if (stateCode == "MO") {
   taxPercentage = 1.0;
} else {
   taxPercentage = 2.0;
}
document.write(taxPercentage);
</script>
</head>
<body>
</body>
</html>


Nested if statement

<html>
<head>
<title>Nested if statement</title>
<script>
var temp = 0;
temp = Math.floor(Math.random() * 100) + 1;
alert ("It"s " + temp + " degrees outside. ");
if (temp < 70){
  if (temp < 30){
    alert("< 30");
  } else {
    alert(" between 30 and 70");
  }
} else {
  if (temp > 85){
    alert("> 85");
  } else {
    alert("between 85 and 70");
  }
}
</script>
</head>
<body>
<h3>Hit Reload to see another temperature</h3>
</body>
</html>


Use if/else to check the returning value from a confirm dialog

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var response = confirm("Do you want to proceed with this book?  Click OK to proceed otherwise click Cancel.");
if ( response == true )
{
   alert("A fine choice!")
}else{
   alert("A not fine choice!")
}
//  -->
</script>
</head>
<body>
</body>
</html>


Use if statement to check the returning value from a confirm dialog

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var response = confirm("Do you want to proceed with this book?  Click OK to proceed otherwise click Cancel.");
if ( response == true )
{
    alert("A fine choice!");
}
//  -->
</script>
</head>
<body>
</body>
</html>


Use if statement to compare the numbers

<html>
<head>
<title>Use if statement to compare the numbers</title>
<script>
var temp = 0;
var perfectTemp = 65;

temp = Math.floor(Math.random() * 100) + 1;
alert ("It"s " + temp + " degrees outside. ");
if (temp < perfectTemp){
  alert("Low!!");
}
</script>
</head>
<body>
<h3>Hit Reload to see another temperature</h3>
</body>
</html>