|
CogSci 3 |
Introduction to Computing | |||||||||||||||||
|
Sample JavaScript Page #4This is exactly the same page as the previous one, but with some subtle changes:
The JavaScript which created the HTML between the lines (<HR>) above is given below.
<HR>
<SCRIPT LANGUAGE="JavaScript">
var Counter; // declare a variable called "Counter"
var Greeting = "Howdy"; // declare a variable and set its value
var HowMany; // This is a different variable from the
// parameter declared and used in PrintBlanks
var Now = new Date(); // create a new "date object" with the current
// time and date from the computer clock
HowMany = Now.getSeconds(); // set HowMany to the current
// seconds on your computers clock
HowMany = HowMany % 5; // seconds run between 0 and 59, to print
// 59 Greetings would be boring, so get
// the *remainder* (% means remainder) of the number
// of seconds after dividing by 5; this will be a number
// between 0 and 4 (inclusive)
document.write( "We'll say " );
document.write( Greeting );
document.write( " " ); // a space between the greeting and number
document.write( HowMany );
document.write( " times <P>" );
/*
* The preceding lines will print: We'll say Howdy 1 times <P>
* when Counter equals 1. How could you fix it to say
* "1 time" when Counter is 1, but "N times" (plural) when Counter is
* not equal to 1?
*/
for( Counter=1; Counter <= HowMany; Counter = Counter+1 ) {
PrintBlanks( Counter-1 ); // Print 1 fewer blanks;
// the blanks will indent the
// greeting that follows
document.write( Greeting ); // the variable
document.write( " <BR>" ); // print HTML <BR> command
}
</SCRIPT>
<HR>
This is another example of how JavaScript creating HTML itself using the document.write() function.
Notice "We'll say ..." line on the page. It is constructed by
several document.write() functions in a row. They have the overall
affect of concatenating their output into a single
line.
Another way to have done this is to concatenate all the arguments in the
consecutive document.write()s
and concatenate them ourselves, like: Still another thing to be aware of is that we could have moved all of the variable declarations into the <HEAD> section. However, we still would have needed to have the embedded JavaScript document.write()s and the for loop right where they are, because that is where we want their effects to appear (on the page). Terms to Know
|