What's a variable? Let's suppose x=5.
x is a variable. The statement x=5 declares that the value of x is now 5. Can x be something else? Sure, x=6. Now x equals 6. (Hence the name "variable"... it's value can vary.)
Can a variable be something other than a number? Sure. How about x="Joe". Now x equals the string "Joe". (A string by the way is a string of characters... and strings are always enclosed in quotes.)
Can the name of a variable be something other than a letter like x? Sure, myname="Joe". Simple.
How can we incorporate this new found knowledge into our function? Easy...
<html> <head> <title></title> <script type="text/javascript"> function HelloWorld() { myname = "Joe"; alert(myname); } </script> </head> <body> <a href="javascript:HelloWorld()">Hello</a> </body> </html>
(Note again that strings are always enclosed in quotes, but variables are not.)
What we have called is the alert method. Think of a method as a command. Javascript has many methods.
We could make it say Hello + variable...
<html>
<head>
<title></title>
<script type="text/javascript">
function HelloWorld()
{
myname = "Joe";
alert("Hello " + myname);
}
</script>
</head>
<body>
<a href="javascript:HelloWorld()">Hello</a>
</body>
</html>
PageTutor.com - Javascript Tutor |
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Javascript Authoring Guide JavaScript FAQ |
Google Groups (Advanced Search) |
Print version of this tutorial available - Get the PageTutor book & CD |