ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾JavaScript£¾JavaScript Notes

Navigator Scripting

Using JavaScript in HTML

JavaScript can be embedded in an HTML document in two ways:

  • As statements and functions using the SCRIPT tag.
  • As event handlers using HTML tags.

The SCRIPT tag

A script embedded in HTML with the SCRIPT tag uses the format: <SCRIPT> JavaScript statements... </SCRIPT>

The optional LANGUAGE attribute specifies the scripting language as follows:

<script type="text/javascript"> JavaScript statements... </SCRIPT>

The HMTL tag, <SCRIPT>, and its closing counterpart, </SCRIPT> can enclose any number of JavaScript statements in a document.

JavaScript is case sensitive.


Example 1: a simple script.

<HTML> <HEAD> <script type="text/javascript"> document.write("Hello net.") </SCRIPT> </HEAD> <BODY> That's all, folks. </td> </tr> </table> <div align="center"> <div id="btm1" class="footer"><script type="text/javascript">btm1();</script></div> <div id="uz_copy_right" class="footer"></div> <div id="btm2" class="footer"><script type="text/javascript">btm2();</script></div> </div> <script type="text/javascript">showfooter();</script> <div align="center"> <div id="btm5" class="footer2"><script type="text/javascript">btm5();</script></div> <div id="btm6" class="footer2"><script type="text/javascript">btm6();</script></div> </div> </body> </html>

Example 1 page display.

Hello net. That's all folks.


Code Hiding

Scripts can be placed inside comment fields to ensure that your JavaScript code is not displayed by old browsers that do not recognize JavaScript. The entire script is encased by HTML comment tags: <!-- Begin to hide script contents from old browsers. // End the hiding here. -->

Defining and Calling Functions

Scripts placed within SCRIPT tags are evaluated after the page loads. Functions are stored, but not executed. Functions are executed by events in the page.

It's important to understand the difference between defining a function and calling the function. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters.


Example 2: a script with a function and comments.

<HEAD> <script type="text/javascript"> <!-- to hide script contents from old browsers function square(i) { document.write("The call passed ", i ," to the function.","<BR>") return i * i } document.write("The function returned ",square(5),".") // end hiding contents from old browsers --> </SCRIPT> </HEAD> <BODY> <BR> All done. </BODY> Example 2 page display.


All done.


The HEAD tag

Generally, you should define the functions for a page in the HEAD portion of a document. Since the HEAD is loaded first, this practice guarantees that functions are loaded before the user has a chance to do anything that might call a function.

Example 3: a script with two functions.

<HEAD> <SCRIPT> <!--- hide script from old browsers function bar() { document.write("<HR ALIGN='left' WIDTH=25%>") } function output(head, level, string) { document.write("<H" + level + ">" + head + "</H" + level + "><P>" + string) } // end hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <SCRIPT> <!--- hide script from old browsers document.write(bar(),output("Make Me Big",3,"Make me ordinary.")) // end hiding from old browsers --> </SCRIPT> <P> Thanks. </BODY>

Example 3 results.

Thanks.


Quotes

Use single quotes (') to delimit string literals so that scripts can distinguish the literal from attribute values enclosed in double quotes. In the previous example, function bar contains the literal 'left' within a double-quoted attribute value. Here's another example: <INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')">

Scripting Event Handlers

JavaScript applications in the Navigator are largely event-driven. Events are actions that occur, usually as a result of something the user does. For example, a button click is an event, as is giving focus to a form element. There is a specific set of events that Navigator recognizes. You can define Event handlers, scripts that are automatically executed when an event occurs.

Event handlers are embedded in documents as attributes of HTML tags to which you assign JavaScript code to execute. The general syntax is

<TAG eventHandler="JavaScript Code"> where TAG is some HTML tag and eventHandler is the name of the event handler.

For example, suppose you have created a JavaScript function called compute. You can cause Navigator to perform this function when the user clicks on a button by assigning the function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">

You can put any JavaScript statements inside the quotes following onClick. These statements get executed when the user clicks on the button. If you want to include more than one statement, separate statements with a semicolon (;).

In general, it is a good idea to define functions for your event handlers because:

  • it makes your code modular-you can use the same function as an event handler for many different items.
  • it makes your code easier to read.

Notice in this example the use of this.form to refer to the current form. The keyword this refers to the current object-in the above example, the button object. The construct this.form then refers to the form containing the button. In the above example, the onClick event handler is a call to the compute() function, with this.form, the current form, as the parameter to the function.

Events apply to HTML tags as follows:

  • Focus, Blur, Change events: text fields, textareas, and selections
  • Click events: buttons, radio buttons, checkboxes, submit buttons, reset buttons, links
  • Select events: text fields, textareas
  • MouseOver event: links

If an event applies to an HTML tag, then you can define an event handler for it. In general, an event handler has the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus.

Many objects also have methods that emulate events. For example, button has a click method that emulates the button being clicked. Note: The event-emulation methods do not trigger event-handlers. So, for example, the click method does not trigger an onClick event-handler. However, you can always call an event-handler directly (for example, you can call onClick explicitly in a script).

Event Occurs when... Event Handler
blur User removes input focus from form element onBlur
click User clicks on form element or link onClick
change User changes value of text, textarea, or select element onChange
focus User gives form element input focus onFocus
load User loads the page in the Navigator onLoad
mouseover User moves mouse pointer over a link or anchor onMouseOver
select User selects form element's input field onSelect
submit User submits a form onSubmit
unload User exits the page onUnload

Example 4: a script with a form and an event handler attribute.

<HEAD> <script type="text/javascript"> function compute(form) { if (confirm("Are you sure?")) form.result.value = eval(form.expr.value) else alert("Please come back again.") } </SCRIPT> </HEAD> <BODY> <FORM> Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=15 > <INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)"> <BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 > <BR> </FORM> </BODY>

Example 4 page display.

Enter an expression:
Result:

Example 5: a script with a form and event handler attribute within a BODY tag.

<HEAD> <script type="text/javascript"> <!--- hide script from old browsers function checkNum(str, min, max) { if (str == "") { alert("Enter a number in the field, please.") return false } for (var i = 0; i < str.length; i++) { var ch = str.substring(i, i + 1) if (ch < "0" || ch > "9") { alert("Try a number, please.") return false } } var val = parseInt(str, 10) if ((val < min) || (val > max)) { alert("Try a number from 1 to 10.") return false } return true } function thanks() { alert("Thanks for your input.") } // end hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <FORM NAME="ex5"> Please enter a small number: <INPUT NAME="num" onChange="if (!checkNum(this.value, 1, 10)) {this.focus();this.select();} else {thanks()}"> </FORM> </BODY>

Example 5 page display.

Enter a number in the field and then click your mouse anywhere OUTSIDE of the field. Depending on what you enter, you will be prompted to enter another number, or thanked.

Please enter a small number:

Tips and Techniques

This section describes various useful scripting techniques.

Updating Pages

JavaScript in Navigator generates its results from the top of the page down. Once something has been formatted, you can't change it without reloading the page. Currently, you cannot update a particular part of a page without updating the entire page. However, you can update a "sub-window" in a frame separately.

Printing

You cannot currently print output created with JavaScript. For example, if you had the following in a page:

<P>This is some text. <SCRIPT>document.write("<P>And some generated text")</SCRIPT> And you printed it, you would get only "This is some text", even though you would see both lines on-screen.

Using Quotes

Be sure to alternate double quotes with single quotes. Since event handlers in HTML must be enclosed in quotes, you must use single quotes to delimit arguments. For example

<FORM NAME="myform"> <INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!" onClick="window.open('stmtsov.html', 'newWin', 'toolbar=no,directories=no')"> </FORM>

Alternatively, you can escape quotes by preceding them by a backslash (\).

Defining Functions

It is always a good idea to define all of your functions in the HEAD of your HTML page. This way, all functions will be defined before any content is displayed. Otherwise, the user might perform some action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error.

Creating Arrays

An array is an ordered set of values that you reference through an array name and an index. For example, you could have an array called emp, that contains employees' names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

JavaScript does not have an explicit array data type, but because of the intimate relationship between arrays and object properties (see JavaScript Object Model), it is easy to create arrays in JavaScript. You can define an array object type, as follows:

function MakeArray(n) {
   this.length = n;
   for (var i = 1; i <= n; i++) {
     this[i] = 0 }
     return this
     }
}

This defines an array such that the first property, length, (with index of zero), represents the number of elements in the array. The remaining properties have an integer index of one or greater, and are initialized to zero.

You can then create an array by a call to new with the array name, specifying the number of elements it has. For example:

emp = new MakeArray(20);

This creates an array called emp with 20 elements, and initializes the elements to zero.

Populating an Array

You can populate an array by simply assigning values to its elements. For example:

emp[1] = "Casey Jones"
emp[2] = "Phil Lesh"
emp[3] = "August West"
and so on.

You can also create arrays of objects. For example, suppose you define an object type named Employees, as follows:

function Employee(empno, name, dept) {
   this.empno = empno;
   this.name = name;
   this.dept = dept;
}

Then the following statements define an array of these objects:

emp = new MakeArray(3)
emp[1] = new Employee(1, "Casey Jones", "Engineering")
emp[2] = new Employee(2, "Phil Lesh", "Music")
emp[3] = new Employee(3, "August West", "Admin")

Then you can easily display the objects in this array using the show_props function (defined in the section on the JavaScript Object Model) as follows:

for (var n =1; n <= 3; n++) {
   document.write(show_props(emp[n], "emp") + "
"); }