JavaScript For Beginners(转载)


Posted in Javascript onJanuary 05, 2007

注:我对原文进行了编辑,对一些词汇标注颜色,方便阅读。本来准备翻译,但是觉得文章简单易懂,而且原文写得很好,所以就不献丑了。希望对JavaScript初学者能有所帮助。你可以跟着作者一起做那些示例代码,等读完文章的时候,你就可以掌握JavaScript的基本操作了,你会发现其实这一切很容易。

Contents
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:  

< 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 <Script language="JavaScript"> and ends with the tag </script>. The code placed between <head> and </head>. Sometimes, people embed the code in the <body> tags:

< html >
< head ></ head >
< body >
< script >
JavaScript For Beginners(转载)..
//  The code embedded in the <body> tags.
</ script >
</ body >
</ html >

Why do we place JavaScript code inside comment fields <!-- and //--> ?
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:  

< 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 hello.js :

document.write("Hello World!")

The external file is simply a text file containing JavaScript code with the file name extension ".js".

Note:

  1. Including an external file only functions reliably across platforms n the version 4 browsers.
  2. The code can't include tags <script language...> and </script>, or you will get an error message.

write and writeln

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

< 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 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.


Document object

The 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, 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.

lastModified

You 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 lastModified property of the document. Notice that we used + to put together This page created by John N. Last update: and document.write.

 

bgColor and fgColor

Lets try playing around with bgColor and fgColor
< script >
document.bgColor
= " black "
document.fgColor
= " #336699 "
</ script >  


Message Box

alert

There are three message boxes: alert, confirm, and prompt. Let's 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.

 

confirm

An example for confirm box: 
window.confirm("Are you sure you want to quit?") 

prompt

Prompt 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()
confirm()
prompt()


Variables and Conditions

Let's 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, 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.

< 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: if(!x) means: if click "cancel". In JavaScript, the exclamation mark !means: "none".


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 <script> </script> 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 line test() calls the function, now you will see the words "Hello can you see me?".


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.

onClick

onClick handlers execute something only when users click on buttons, links, etc. Let's see an example:
< script >
function  ss()
{
alert(
" Thank you! "
)
}
</ script >

< form >
< input  type ="button"  value ="Click here"  onclick ="ss()" >
</ form >

The function ss() is invoked when the user clicks the button. Note: Event handlers are not added inside the <script> tags, but rather, inside the html tags.

onLoad

The 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,onMouseout

These handlers are used exclusively with links.
< href ="#"  onMouseOver ="document.write('Hi, nice to see you!" > Over Here! </ a >
< href ="#"  onMouseOut ="alert('Good try!')" > Get Out Here! </ a >

onUnload

onUnload 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 actions

How 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: 
< form >
< input  type ="button"  value ="Click here!"  onClick ="alert('Thanks for visiting my site!');window.location='http://www.yahoo.com'" >
</ form >
 


Form

Let's 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.

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: 
< 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 @, 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("@")==-1basically 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 <form> tag, and not inside any one element. Lets do an example:    
< 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:
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 
< 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 >

|| 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 ('Invalid Login') and stop submitting. Else, open the page 'main.htm'".
 

Link

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

< href ="JavaScript:window.location.reload()" > Click to reload! </ a >

More examples:        

< href ="#"  onClick ="alert('Hello, world!')" > Click me to say Hello </ a >< br >

< href ="#"  onMouseOver ="location='main.htm'" > Mouse over to see Main Page </ a >



Date

Let's 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: 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 pages

You 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' > ") 
 
Date object
Methods
getDate getTimegetTimezoneOffset getDaygetMonthgetYear getSecondsgetMinutesgetHours


Window

Open a window

To 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 test.htm with any URL, for example, with http://www.yahoo.com

 

Size, toolbar, menubar, scrollbars, location, status

Let'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: 
 
< 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:
width height toolbar
location directories status
scrollbars resizable menubar

Reload

To reload a window, use this method:           
   
window.location.reload()

Close Window

Your can use one of the codes shown below: 
< form >
< input  type ="button"  value ="Close Window"  onClick ="window.close()" >
</ form >
< href ="javascript:window.close()" > Close Window </ a >
 

Loading

The basic syntax when loading new content into a window is: 
 
window.location="test.htm"

This is the same as   
< href ="test.htm>Try this </a>

Let's 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 Window

Let'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('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("This is a test.").

Now, let's 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 >

 

opener

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

 

Let's 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 test.htm): 
 

< html >
< head >
< title ></ title >
< script >
function  remote(url){
window.opener.location
=
url
}
</ script >

</ head >
< body >
< p >< href ="#"  onClick ="remote('file1.htm')" > File1 </ a ></ p >
< p >< href ="#"  onClick ="remote('file2.htm')" > File2 </ 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 >
< href ="page3.htm"
onClick
="parent.frame2.location='page4.htm'" > Click Here </ a >
</ body >
</ html >

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

Source:http://www.codeproject.com/jscript/jsbeginner.asp

Javascript 相关文章推荐
input+select(multiple) 实现下拉框输入值
May 21 Javascript
JavaScript加入收藏夹功能(兼容IE、firefox、chrome)
May 05 Javascript
JS显示日历和天气的方法
Mar 01 Javascript
jQuery简单实现点击文本框复制内容到剪贴板上的方法
Aug 01 Javascript
AngularJS下对数组的对比分析
Aug 24 Javascript
JavaScript定义全局对象的方法示例
Jan 12 Javascript
微信小程序中子页面向父页面传值实例详解
Mar 20 Javascript
微信小程序 图片宽高自适应详解
May 11 Javascript
基于JSONP原理解析(推荐)
Dec 04 Javascript
微信小程序使用wxParse解析html的方法教程
Jul 06 Javascript
JavaScript惰性载入函数实例分析
Mar 27 Javascript
解决vue admin element noCache设置无效的问题
Nov 12 Javascript
JavaScript的目的分析
Jan 05 #Javascript
关于JavaScript的gzip静态压缩方法
Jan 05 #Javascript
关于Javascript 的 prototype问题。
Jan 03 #Javascript
彻底搞懂JS无缝滚动代码
Jan 03 #Javascript
经典的解除许多网站无法复制文字的绝招
Dec 31 #Javascript
对象的类型:本地对象(1)
Dec 29 #Javascript
JavaScript高级程序设计
Dec 29 #Javascript
You might like
PHP使用PHPExcel删除Excel单元格指定列的方法
2016/07/06 PHP
PHP simplexml_load_string()函数实例讲解
2019/02/03 PHP
ThinkPHP3.2.3框架实现的空模块、空控制器、空操作,跳转到错误404页面图文详解
2019/04/03 PHP
前淘宝前端开发工程师阿当的PPT中有JS技术理念问题
2010/01/15 Javascript
基于jQuery的试卷自动排版系统实现代码
2011/01/06 Javascript
我的javascript 函数链之演变
2011/04/07 Javascript
jQuery EasyUI API 中文文档 - ComboGrid 组合表格
2011/10/13 Javascript
SOSO地图API使用(一)在地图上画圆实现思路与代码
2013/01/15 Javascript
javascript框架设计读书笔记之模块加载系统
2014/12/02 Javascript
javascript框架设计读书笔记之数组的扩展与修复
2014/12/02 Javascript
jQuery()方法的第二个参数详解
2015/04/29 Javascript
JavaScript判断IE版本型号
2015/07/27 Javascript
js仿百度音乐全选操作
2017/01/13 Javascript
JavaScript通过改变文字透明度实现的文字闪烁效果实例
2017/04/27 Javascript
Angularjs中使用轮播图指令swiper
2017/05/30 Javascript
解决Vue编译时写在style中的路径问题
2017/09/21 Javascript
es6新特性之 class 基本用法解析
2018/05/05 Javascript
在微信小程序中保存网络图片
2019/02/12 Javascript
vue 中使用 watch 出现了如下的报错的原因分析
2019/05/21 Javascript
微信小程序非跳转式组件授权登录的方法示例
2019/05/22 Javascript
Vue.use()在new Vue() 之前使用的原因浅析
2019/08/26 Javascript
uni-app从安装到卸载的入门教程
2020/05/15 Javascript
vue利用全局导航守卫作登录后跳转到未登录前指定页面的实例代码
2020/05/19 Javascript
js验证账户名是否重复
2020/05/26 Javascript
原生javascript如何实现共享onload事件
2020/07/03 Javascript
openlayers4实现点动态扩散
2020/08/17 Javascript
django模板结构优化的方法
2019/02/28 Python
使用 Supervisor 监控 Python3 进程方式
2019/12/05 Python
python为Django项目上的每个应用程序创建不同的自定义404页面(最佳答案)
2020/03/09 Python
Python 随机生成测试数据的模块:faker基本使用方法详解
2020/04/09 Python
TensorFlow keras卷积神经网络 添加L2正则化方式
2020/05/22 Python
MxNet预训练模型到Pytorch模型的转换方式
2020/05/25 Python
西班牙伏林航空公司:Vueling
2016/08/05 全球购物
Timberland澳大利亚官网:全球领先的户外品牌
2019/12/10 全球购物
单位委托书格式范本
2014/09/29 职场文书
Mysql排查分析慢sql之explain实战案例
2022/04/19 MySQL