国外的为初学者写的JavaScript教程 |
|||||||||||||||
Embedding and includingLets first see a simple example: <html> <head> <title>This is a JavaScript example</title> <script language="JavaScript"> <!-- document.write("Hello World!"); //--> </script> </head> <body> Hi, man! </body> </html> Usually, JavaScript code starts with the tag <html> <head></head> <body> <script> .....// The code embedded in the <body> tags. </script> </body> </html> Why do we place JavaScript code inside comment fields <script language="JavaScript1.2"> You can use another attribute SRC to include an external file containing JavaScript code: <script language="JavaScript" src="hello.js"></script> For example, shown below is the code of the external file document.write("Hello World!") The external file is simply a text file containing JavaScript code with the file name extension ".js". Note:
Back to top write and writelnIn order to output text in JavaScript you must use <HTML> <HEAD> <TITLE> Welcome to my site</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- document.write("Welcome to my site!"); // --> </SCRIPT> </BODY> </HTML> Note: the document object Back to top Document objectThe document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScript code: document.write("Hi there.") In this code,
lastModifiedYou can always include the last update date on your page by using the following code:<script language="JavaScript"> document.write("This page created by John N. Last update:" + document.lastModified); </script> All you need to do here is use the
bgColor and fgColorLets try playing around withbgColor and fgColor :
<script> document.bgColor="black" document.fgColor="#336699" </script> Back to top Message Box
alertThere are three message boxes:alert , confirm , and prompt . Lets look at the first one: <body> <script> window.alert("Welcome to my site!") </script> </body> 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 alert() confirm() prompt() Back to top Variables and ConditionsLets see an example: <script> var x=window.confirm("Are you sure you want to quit") if (x) window.alert("Thank you.") else window.alert("Good choice.") </script> There are several concepts that we should know. First of all, <script> var y=window.prompt("please enter your name") window.alert(y) </script> Another example: <html><head> <script> var x=confirm("Are you sure you want to quit?") if (!x) window.location="http://www.yahoo.com" </script> </head> <body> Welcome to my website!. </body></html> 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: Back to top FunctionFunctions are chunks of code.Lets create a simple function: function test() { document.write("Hello can you see me?") } Note that if only this were within your function test() { document.write("Hello can you see me?") } test() Last line Back to top Event handlerWhat 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. Lets see an example:
<script> function ss() { alert("Thank you!") } </script> <form> <input type="button" value="Click here" onclick="ss()"> </form> The function
onLoadThe onload event handler is used to call the execution of JavaScript after loading:<body onload="ss()"> <frameset onload="ss()"> <img src="whatever.gif" onload="ss()">
onMouseover,onMouseoutThese handlers are used exclusively with links.<a href="#" onMouseOver="document.write(Hi, nice to see you!">Over Here!</a> <a href="#" onMouseOut="alert(Good try!)">Get Out Here!</a>
onUnloadonunload executes JavaScript while someone leaves the page. For example to thank users.
<body onunload="alert(Thank you for visiting us. See you soon)">
Handle multiple actionsHow do you have an event handler call multiple functions/statements? Thats simple. You just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:<form> <input type="button" value="Click here!" onClick="alert(Thanks for visiting my site!);window.location=http://www.yahoo.com"> </form> Back to top FormLets say you have a form like this: <form name="aa"> <input type="text" size="10" value="" name="bb"><br> <input type="button" value="Click Here"onclick="alert(document.aa.bb.value)"> </form> Notice that we gave the names to the form and the element. So JavaScript can gain access to them.
onBlurIf 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 useonBlur . Lets see how onblur works:
<html><head><script> function emailchk() { var x=document.feedback.email.value if (x.indexOf("@")==-1) { alert("It seems you entered an invalid email address.") document.feedback.email.focus() } } </script></head><body> <form name="feedback"> Email:<input type="text" size="20" name="email" onblur="emailchk()"><br> Comment: <textarea name="comment" rows="2" cols="20"></textarea><br> <input type="submit" value="Submit"> </form> </body></html> If you enter an email address without the alert("It seems you entered an invalid email address.") document.feedback.email.focus() Whats <script> <!-- function validate() { if(document.login.userName.value=="") { alert ("Please enter User Name") return false } if(document.login.password.value=="") { alert ("Please enter Password") return false } } //--> </script> <form name="login" onsubmit="return validate()"> <input type="text" size="20" name="userName"> <input type="text" size="20" name="password"> <input type="submit" name="submit" value="Submit"> </form> Note:
Protect a file by using LoginLets try an example<html><head> <SCRIPT Language="JavaScript"> function checkLogin(x) { if ((x.id.value != "Sam")||(x.pass.value !="Sam123")) { alert("Invalid Login"); return false; } else location="main.htm" } </script> </head><body> <form> <p>UserID:<input type="text" name="id"></p> <p>Password:<input type="password" name="pass"></p> <p><input type="button" value="Login" onClick="checkLogin(this.form)"></p> </form> </body></html>
Back to top LinkIn most cases, a form can be repaced by a link: <a href="JavaScript:window.location.reload()">Click to reload!</a> More examples: <a href="#" onClick="alert(Hello, world!)">Click me to say Hello</a><br> <a href="#" onMouseOver="location=main.htm">Mouse over to see Main Page</a> Back to top DateLets see an example: <HTML><HEAD><TITLE>Show Date</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> var x= new Date(); document.write (x); </SCRIPT> </BODY></HTML> To activate a Date Object, you can do this:
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() if (ss<=12) document.write("<img src=banner1.gif>") else document.write("<img src=banner2.gif>")
Window
Open a windowTo open a window, simply use the method "window.open()":<form> <input type="button" value="Click here to see" onclick="window.open(test.htm)"> </form> You can replace
Size, toolbar, menubar, scrollbars, location, statusLets 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: <form> <input type="button" value="Click here to see" onclick="window.open(page2.htm,win1,width=200,height=200,menubar)"> </form> Another example with no attributes turned on, except the size changed: <form> <input type="button" value="Click here to see" onclick="window.open(page2.htm,win1,width=200,height=200)"> </form> Here is the complete list of attributes you can add:
ReloadTo reload a window, use this method:window.location.reload()
Close WindowYour can use one of the codes shown below:<form> <input type="button" value="Close Window" onClick="window.close()"> </form> <a href="javascript:window.close()">Close Window</a>
LoadingThe basic syntax when loading new content into a window is:window.location="test.htm" This is the same as <a href="test.htm>Try this </a> Lets provide an example, where a confirm box will allow users to choose between going to two places: <script> <!-- function ss() { var ok=confirm(Click "OK" to go to yahoo, "CANCEL" to go to hotmail) if (ok) location="http://www.yahoo.com" else location="http://www.hotmail.com" } //--> </script>
Remote Control WindowLets 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(test.htm,,width=200,height=200) By giving this window a name "aa", it will give you access to anything thats inside this window from other windows. Whenever we want to access anything thats inside this newly opened window, for example, to write to this window, we would do this: aa.document.write("This is a test."). Now, lets see an example of how to change the background color of another window: <html><head><title></title></head> <body> <form> <input type="button" value="Open another page" onClick="aa=window.open(test.htm,,width=200,height=200)"> <input type="radio" name="x" onClick="aa.document.bgColor=red"> <input type="radio" name="x" onClick="aa.document.bgColor=green"> <input type="radio" name="x" onClick="aa.document.bgColor=yellow"> </form> </body></html>
openerUsing"opener" property, we can access the main window from the newly opened window.
Lets create Main page: <html> <head> <title></title> </head> <body> <form> <input type="button" value="Open another page" onClick="aa=window.open(test.htm,,width=100,height=200)"> </form> </body> </html> Then create Remote control page (in this example, that is <html> <head> <title></title> <script> function remote(url){ window.opener.location=url } </script> </head> <body> <p><a href="#" onClick="remote(file1.htm)">File 1</a></p> <p><a href="#" onClick="remote(file2.htm)">File 2</a></p> </body> </html> 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: <html> <frameset cols="150,*"> <frame src="page1.htm" name="frame1"> <frame src="page2.htm" name="frame2"> </frameset> </html> 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: <html> <body> <h2>This is page 1 </h2> <a href="page3.htm" onClick="parent.frame2.location=page4.htm">Click Here</a> </body> </html> Notice: You should use
|