JavaScript Learning Essays (writing browser scripts Navigator scripting) _javascript tips

Source: Internet
Author: User
Tags eval html page html tags object model script tag

Using JavaScript in HTML

JavaScript can embed HTML in two ways:

    • When used as statements and functions, use the SCRIPT tag
    • When used as an event handler, the HTML tag

SCRIPT tag

Use script tags to embed scripts in HTML, in the form of a broadside:

<SCRIPT>
_ JavaScript Statement
</SCRIPT>

The Language property is used as an option to specify the scripting language, as follows:

<script language= "JavaScript" >
_javascript statement
</SCRIPT>

</SCRIPT> is the closing flag of <SCRIPT>, which can include as many JavaScript statements as possible.

JavaScript is a case-sensitive file


example of 11 simple scripts

<HTML>
<HEAD>
<script language= "JavaScript" >
document.write ("Hello net.")
</SCRIPT>
</HEAD>
<BODY>
So ' s all, folks.
</BODY>
</HTML>

The page in Example 1 shows:

Hello Net. That ' s all folks.


Code Stealth

On older browsers that do not recognize JavaScript, you can place the script in the annotation field so that the JavaScript code is not displayed. Enclose the entire script in an HTML annotation tag:

<!--begin to hide the script content and not be displayed by the old version browser
Concealment ends here. -->

Defining and calling Functions

After the page is loaded, the script that is placed between the script tags is parsed. The function is stored, but not executed. Functions are executed by an event call within a page.

It is important to correctly understand the difference between defining a function and calling a function, and defining a function is simply naming the function and explaining what to do when the function is called, and the calling function is actually performing the specified action with the arguments that came.

Example 21 script with functions and annotations

<HEAD>
<script language= "JavaScript" >
<!--begin to hide the script content and not be displayed by the old version browser
function Square (i) {
document.write ("The call passed", I, "to the function.", "<BR>")
Return I*i
}
document.write ("The function returned", Square (5), ".")
Concealment ends here. -->
</SCRIPT>
</HEAD>
<BODY>
<BR>
All done.
</BODY>


The page in Example 2 shows:

We passed 5 to the function.
The function returned 25.
All done.

Head Mark

In general, you should define all the functions of the page in the Head section of the document, because the head is loaded first, which ensures that the function is fully loaded before the user does any action that might invoke the function.

Example 3 has two functions in a script.

<HEAD>
<SCRIPT>
<!---hide script from old browsers
function Bar () {
document.write ("}
function output (head,level,string) {
document.write ("}
End hiding from old browsers-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT>
<!---hide script from old browers
document.write (bar (), Output ("Make Me Big", 3, "Make Me ordinary.")
End hiding from old browsers-->
</SCRIPT>
<P>
Hi.
</BODY>

Result of Example 3:

Make Me Big
Make Me ordinary.undefinedundefined
Hi.

Quotes

Enclose the string constants in single quotes ('), enclose the values of the attributes in double quotes so that the script can separate the two areas. In the last example, in function bar, the constant left is placed in the property value. Another example:

<input type= "button" value= "Press Me" onclick= "MyFunc (' astring ')" >

Writing an event handler script (scripting event handlers)

Most of the JavaScript applications on Navigator are event-driven, and events are often the result of user actions. For example: The push button is an event, and the result is assigning the focus to a FORM element. Navigator can identify a specific set of events. You can define the event handlers script that will be executed automatically when the event occurs.

An event handler is placed in the document as an attribute of the HTML tag, assigning the JavaScript code to the HTML tag. The syntax is as follows:

<tag eventhandler= "JavaScript Code" >

Where tag is a tag of HTML, EventHandler is the name of the event handler.

For example, assuming you have created a JavaScript function named COMPUTE, you can assign a call to the function to the button's OnClick event handler to implement the Navigator function compute when the user presses the button.

<input type= "button" value= "Calculate" onclick= "compute (this.form)" >

You can place any JavaScript statement within the onclick quotation mark, separated by semicolons. These statements are executed only when the user presses the button.

Generally, it is a good practice to define your own event handlers as functions:

    • This makes your code modular---the same function can act as an event handler for multiple different item.
    • This makes your code easy to read.

Note that in this example, the this.form is used to refer to the current form, where the keyword this refers to the current object, which is the button object, and the this.form structure is used to refer to the form that contains the button. The OnClick event handler in the previous example calls the compute () function with the This.form (current form) as the parameter.

The events that can be used in HTML tags are as follows:

    • Focus, Blur, change events: Text field, text area, and selection
    • Click event: Button, wireless button, check box, submit button, reset button, link
    • Select event: Text field, text area
    • MouseOver Event: Link

If an event is available in an HTML tag, you can define an event handler for it. Usually the name of the event handler begins with on, followed by the event name. For example, the focus handler name is onfocus.

Many objects have methods that simulate events (method). For example, a button has a method named Click to simulate the buttons being pressed. Note: The method of simulating an event cannot trigger an event handler. If the method click does not trigger an event handler onclick. However, you can invoke the event handler directly (for example, in a script, explicitly invoke onclick).

Event When it happens Event handlers
Blur The user removes the input focus from the form element OnBlur
Click The user moves the mouse over a form element or connection OnClick
Change The user changed the text, text area, or the value of the selection element OnChange
Focus User assigns input focus to form element onfocus
Load The user loads the page into the Navigato OnLoad
MouseOver The user moves the mouse cursor over link or anchor Onmouseove
Select The user selects the input field for the form element Onselect
Submit The user submits a form OnSubmit
Unload User exits this page OnUnload


Example 4 script that has a form and an event handler property

<HEAD>
<script language= "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= "expr" size=15>
<BR>
</FORM>
</BODY>

The page display in Example 4

Enter An expression:
Result:


Example 5 has a form script, the event handler property is placed in the body tag

<HEAD>
<script language= "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 Hi () {
Alert ("Thank for your input.")
}
End hiding from old browsers-->
</SCRIPT>
</HEAD>

<BODY>
<form name= "Ex5" >
Enter a small number:
<input name= "num"
Onchange= "If" (!checknum (this.valu,1,10))
{This.focus (); this.select; else thanks ()} ">
</FORM>
</BODY>

The page display in Example 5

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

Enter a small number:

Techniques and Techniques

This section describes several useful scripting techniques

Update page (updating pages)

On navigator, JavaScript generates results in the order from the top of the page to the bottom. Once something has been redesigned (format), you can only change it by reloading the page, and at the moment you can only update the entire page, not just one part. But you can update the "Sub-window" in the frame individually.

Print

Currently, you can't print out the output produced with JavaScript. For example, if your page has the following content,

<p>this is some text
<script>document.write ("<p>and some generated text") </SCRIPT>

When printing, you will only make "This is some text", even if you can see two lines on the screen.

Use quotation marks

Be sure to distinguish between double quotes and single quotes, because the event handlers in HTML must be enclosed in double quotes, in single quotes, 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 use the forward backslash (\) to escape the quotes.

Defining functions

It's a good practice to define all the functions in the Head section of an HTML page. This way, all functions are defined before any content is displayed. Otherwise, when the page is still loading, the user may do something to trigger the event handler and call the undefined function, resulting in an error.

Create an array

An array is a collection of ordered values, referenced by an array name and index. For example, an array named EMP holds the name of an employee and is indexed by employee number. So, emp[1] is number 1th, emp[2] is employee number 2nd, and so on.

There is no explicit array data type in JavaScript, but because arrays are similar to objects (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 in which the first property length represents the number of elements in the array (indexed as 0), the remaining property initial values are 0, and the index is an integer greater than or equal to 1.

When new is called, an array is created with the number of array names and arrays of elements.

Emp=new Makearray (20);

The statement creates an array named EMP with 20 elements and an initial value of 0.

Action Array (populating an array)

Manipulate an array by assigning values to an array element. For example:

emp[1]= "Casey Jones."
emp[2]= "PHil Lesh"
emp[3]= "August West"

Wait a minute.

You can also create an array of objects. For example, define an object type named Employees:

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

The following statement creates an array of this object:

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", "" Admin)

At this point, the function show_props (defined in JavaScript object model) is used to display the objects in the array as follows:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.