<script type="text/javascript"> var r=Math.random() if (r>0.5) { document.write("<a href='http://www.w3schools.com'>Learn Web Development!</a>") } else { document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!</a>") } </script>
</body> </html>
多条件的语句实现的例子:
<html> <body> <script type="text/javascript"> var d = new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") break case 0: document.write("Sleepy Sunday") break default: document.write("I'm really looking forward to this weekend!") } </script>
<p>This example demonstrates the switch statement.</p>
<p>You will receive a different greeting based on what day it is.</p>
<p>Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>
</body> </html>
循环的例子:
for循环的一个例子:
<html> <body>
<script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("The number is " + i) document.write("<br>") } </script>
<p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body> </html>
复杂循环的一个例子:
<html> <body>
<script type="text/javascript"> for (i = 1; i <= 6; i++) { document.write("<h" + i + ">This is header " + i) document.write("</h" + i + ">") } </script>
</body> </html>
按条件循环while的例子:
<html> <body>
<script type="text/javascript"> i = 0 while (i <= 5) { document.write("The number is " + i) document.write("<br>") i++ } </script>
<p>Explanation:</p>
<p><b>i</b> equal to 0.</p>
<p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p>
<p><b>i</b> will increase by 1 each time the loop runs.</p>
</body> </html>
do...while循环的例子:
<html> <body>
<script type="text/javascript"> i = 0 do { document.write("The number is " + i) document.write("<br>")