国外的为初学者写的JavaScript教程_基础知识_脚本之家

Embedding and including write and writeln Document object Message box
Function Event handler Form Link Date Window Frame Embedding and
including

Let’s first see a simple example:

  This is a JavaScript example  <!-- document.write; //-->    Hi, man!  

Usually, JavaScript code starts with the tag “

and ends with the tag . The code placed between and . Sometimes,
people embed the code in the
tags:

    .....// The code embedded in the <body> tags.   

Why do we place JavaScript code inside comment fields “? It’s for
ensuring that the Script is not displayed by old browsers that do not
support JavaScript. This is optional, but considered good practice. The
LANGUAGE attribute also is optional, but recommended. You may specify a
particular version of JavaScript:

You can use another attribute SRC to include an external file containing
JavaScript code:

For example, shown below is the code of the external file hello.js:

document.write

The external file is simply a text file containing JavaScript code with
the file name extension “.js”. Note: Including an external file only
functions reliably across platforms in the version 4 browsers. The code
can’t include tags “

and “, or you will get an error message.

Back to top

write and writeln

In order to output text in JavaScript you must use write() or
writeln(). Here’s an example:

   Welcome to my site   <!-- document.write("Welcome to my site!"); // -->   

Note: the document object write is in lowercase as JavaScript is case
sensitive. The difference between write and writeln is: write just
outputs a text, writeln outputs the text and a line break.

Back to top

Document object

The document object is one of the most important objects of JavaScript.
Shown below is a very simple JavaScript code:

document.write

In this code, document is the object. write is the method of this
object. Let’s have a look at some of the other methods that the document
object possesses.

lastModifiedYou can always include the last update date on your page by
using the following code:

  document.write("This page created by John N. Last update:" + document.lastModified);  

All you need to do here is use the lastModified property of the
document. Notice that we used + to put together This page created by
John N. Last update:
and document.lastModified.

bgColor and fgColorLets try playing around with bgColor and fgColor:

 document.bgColor="black" document.fgColor="#336699"  

Back to top

Message Box

alertThere are three message boxes: alert, confirm, and prompt.
Let’s look at the first one:

  window.alert("Welcome to my site!")  

You can put whatever you want inside the quotation marks.

confirmAn example for confirm box:

 window.confirm("Are you sure you want to quit?") 

promptPrompt box is used to allow a user to enter something according
the promotion:

 window.prompt("please enter user name") 

In all our examples above, we wrote the box methods as window.alert().
Actually, we could simply write the following instead as:

alert

Back to top

Variables and Conditions

Let’s see an example:

 var x=window.confirm("Are you sure you want to quit") if  window.alert else window.alert 

There are several concepts that we should know. First of all, var x=
is a variable declaration. If you want to create a variable, you must
declare the variable using the var statement. x will get the result,
namely, true or false. Then we use a condition statement if else
to give the script the ability to choose between two paths, depending on
this result (condition for the following action). If the result is true
(the user clicked “ok”), “Thank you” appears in the window box. If the
result is false (the user clicked “cancel”), “Good choice” appears in
the window box instead. So we can make more complex boxes using var,
if and those basic methods.

 var y=window.prompt("please enter your name") window.alert 

Another example:

  var x=confirm("Are you sure you want to quit?") if  window.location="http://www.yahoo.com"    Welcome to my website!. 

If you click “cancel”, it will take you to yahoo, and clicking ok will
continue with the loading of the current page “Welcome to my website!”.
Note:ifmeans: if click “cancel”. In JavaScript, the exclamation mark
! means: “none”.

Back to top

Function

Functions are chunks of code.Let’s create a simple function:

function test() { document.write("Hello can you see me?") }

Note that if only this were within your “

tags, you will not see “Hello can you see me?” on your screen because
functions are not executed by themselves until you call upon them. So we
should do something:

function test() { document.write("Hello can you see me?") } test() 

Last linetest() calls the function, now you will see the words “Hello
can you see me?”.

Back to top

Event handler

What are event handlers? They can be considered as triggers that execute
JavaScript when something happens, such as click or move your mouse over
a link, submit a form etc.

onClickonClick handlers execute something only when users click on
buttons, links, etc. Let’s see an example:

 function ss() { alert }  

The function ss() is invoked when the user clicks the button. Note:
Event handlers are not added inside the “

tags, but rather, inside the html tags.

onLoad The onload event handler is used to call the execution of
JavaScript after loading:

onMouseover,onMouseoutThese handlers are used exclusively with links.

Over Here! Get Out Here!

onUnloadonunload executes JavaScript while someone leaves the page.
For example to thank users.

Handle multiple actionsHow do you have an event handler call multiple
functions/statements? That’s simple. You just need to embed the
functions inside the event handler as usual, but separate each of them
using a semicolon:

Back to top

Form

Let’s say you have a form like this:

Notice that we gave the names to the form and the element. So JavaScript
can gain access to them.

欧洲杯买球下注盘口 ,onBlur If you want to get information from users and want to check each
element (ie: user name, password, email) individually, and alert the
user to correct the wrong input before moving on, you can use onBlur.
Let’s see how onblur works:

 function emailchk() { var x=document.feedback.email.value if  { alert("It seems you entered an invalid email address.") document.feedback.email.focus() } } 

If you enter an email address without the @, you’ll get an alert
asking you to re-enter the data. What is: x.indexOf==-1? This is a
method that JavaScript can search every character within a string and
look for what we want. If it finds it will return the position of the
char within the string. If it doesn’t, it will return -1. Therefore,
x.indexOf==-1 basically means: “if the string doesn’t include @, then:

alert("It seems you entered an invalid email address.") document.feedback.email.focus()

What’s focus()? This is a method of the text box, which basically
forces the cursor to be at the specified text box. onsubmitUnlike
onblur, onsubmit handler is inserted inside the “

Note:if(document.login.userName.value==""). This means “If the box
named userName of the form named login contains nothing, then…”.
return false. This is used to stop the form from submitting. By default,
a form will return true if submitting. return validate() That means,
“if submitting, then call the function validate()".

Protect a file by using Login Let’s try an example

  function checkLogin { if ||(x.pass.value !="Sam123")) { alert; return false; } else location="main.htm" } 

|| means “or”, and ,!= indicates “not equal”. So we can explain the
script: “If the id does not equal ‘Sam’, or the password does not equal
‘Sam123’, then show an alert and stop submitting. Else, open the page
‘main.htm'”.

Back to top

Link

In most cases, a form can be repaced by a link:

Click to reload!

More examples:

Click me to say Hello

Mouse over to see Main Page

Back to top

Date

Let’s see an example:

Show Date   var x= new Date;  

To activate a Date Object, you can do this: var x=new Date(). Whenever
you want to create an instance of the date object, use this important
word: new followed by the object name().

Dynamically display different pagesYou can display different pages
according to the different time. Here is an example:

var banTime= new Date() var ss=banTime.getHours document.write("") else document.write("") 

Date object

MethodsgetDate getTimegetTimezoneOffsetgetDaygetMonthgetYear
getSecondsgetMinutesgetHours

Window

Open a windowTo open a window, simply use the method “window.open()”:

You can replace https://www.jb51.net/article/test.htm with any URL,
for example, with http://www.yahoo.com.

Size, toolbar, menubar, scrollbars, location, statusLet’s add some of
attributes to the above script to control the size of the window, and
show: toolbar, scrollbars etc. The syntax to add attributes is:

open("URL","name","attributes")

For example:

Another example with no attributes turned on, except the size changed:

Here is the complete list of attributes you can add:

widthheighttoolbarlocationdirectoriesstatusscrollbarsresizablemenubar

Reload To reload a window, use this method:

window.location.reload()

Close WindowYour can use one of the codes shown below:

 Close Window

LoadingThe basic syntax when loading new content into a window is:

window.location="https://www.jb51.net/article/test.htm"

This is the same as

Remote Control WindowLet’s say you have opened a new window from the
current window. After that, you will wonder how to make a control
between the two windows. To do this, we need to first give a name to the
window.Look at below:

aa=window.open('https://www.jb51.net/article/test.htm','','width=200,height=200')

By giving this window a name “aa”, it will give you access to anything
that’s inside this window from other windows. Whenever we want to access
anything that’s inside this newly opened window, for example, to write
to this window, we would do this: aa.document.write.

Now, let’s see an example of how to change the background color of
another window:

openerUsing "opener" property, we can access the main window from the
newly opened window.

Let’s create Main page:

Then create Remote control page (in this example, that is
https://www.jb51.net/article/test.htm):

    function remote{ window.opener.location=url }    File 1 File 2  

Try it now!

Frame

One of the most popular uses of loading multiple frames is to load and
change the content of more than one frame at once. Lets say we have a
parent frame:

We can add a link in the child frame “frame1” that will change the
contents of not only page1, but page2 too. Shown below is the html code
for it:

   This is page 1  Click Here  

Notice: You should use "parent.frameName.location" to access another
frame. “parent” standards for the parent frame containing the frameset
code.

相关文章