You are on page 1of 24

JAVASCRIPT

Bai 1: TONG QUAN VE JAVASCRIPT.


1. ac tnh cua ngon ng Javascript:

avascript la mot ngon ng thong dch (interpreter), chng trnh nguon cua no c nhung (embedded) hoac tch hp (integated) vao tap tin HTML chuan. Khi file c load trong Browser (co support cho JavaScript), Browser se thong dch cac Script va thc hien cac cong viec xac nh. Chng trnh nguon JavaScript c thong dch trong trang HTML sau khi toan bo trang c load nhng trc khi trang c hien th. Javascript la mot ngon ng co ac tnh: n gian. ong (Dynamic). Hng oi tng (Object Oriented).

2. Ngon ng JavaScript:
Mot trong nhng ac tnh quan trong cua ngon ng JavaScript la kha nang tao va s dung cac oi tng (Object). Cac Object nay cho phep ngi lap trnh s dung e phat trien ng dung. Trong JavaScript ,cac Object c nhn theo 2 kha canh: a. Cac Object a ton tai. b. Cac Object do ngi lap trnh xay dng. Trong cac Object a ton tai c chia thanh 2 kieu: a. Cac Object cua JavaScript (JavaScript Built-in Object). b. Cac oi tng c cung cap bi moi trng Netscape.

3. Built-in Object trong JavaScript:


JavaScript cung cap 1 bo cac Built-in Object e cung cap cac thong tin ve s hien hanh cua cac oi tng c load trong trang Web va noi dung cua no.Cac oi tng nay bao gom cac phng phap (Method) lam viec vi cac thuoc tnh (Properties) cua no.

4. Cac oi tng c cung cap bi moi trng Netscape:


Netscape Navigator cung cap cac oi tng cho phep JavaScript tng tac vi file HTML, cac oi tng nay cho phep chung ta ieu khien viec hien th thong tin va ap ng cac s kien trong moi trng Navigator.V du oi tng Window Mo ta Cung cap cac phng phap va cac tnh chat cho ca so hien hanh cua trnh duyet,bao gom cac oi tng cho moi frame.

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 1

Location History Document

Cung cap cac tnh chat va phng phap lam viec vi cac a ch URL hien hanh c m. Cac oi tng history cung cap thong tin ve cac danh sach cu va co the gii han s tng tac vi danh sach. ay la mot oi tng c s dung nhieu nhat .No cha ng cac oi tng,tnh chat va cac phng phap lam viec vi cac thanh phan cua tai lieu nh cac :form,link,anchor,applet.

5. Cac oi tng do ngi lap trnh xay dng:


a. nh ngha thuoc tnh cua oi tng: (Object Properties) Cu phap : Object-name.Property-name (ten oi tng.ten ac tnh) V du :Mot oi tng airplane co cac thuoc tnh nh sau: Airplane.model Airplane.maxspeed Airplane.price Airplane.fuel Airplane.seating b. Them cac phng phap cho oi tng:( Method to Object) Sau khi a co cac thong tin ve airplane ta tiep tuc xay dng phng phap e s dung thong tin nay.V du ban muon in ra mo ta cua airplane hoac tnh toan khoang cach toi a cua cuoc hanh trnh vi nhien lieu a co: Airplane.description() Airplane.distance() c. Tao mot instance cua oi tng: Trc khi thao tac vi mot oi tng cua JavaScript ta phai tao mot instance cho oi tng o.

6 . Nhung JavaScript vao trong tap tin HTML:


Cu phap: <SCRIPT LANGUAGE=JavaScript> JavaScript Program </SCRIPT> Thuoc tnh cua the SCRIPT + SRC :a ch URL ch en tap tin chng trnh JavaScript (*.js) + LANGUAGE: Ch nh ngon ng c s dung trong Script va cac phien ban s dung (v du nh :JavaScript ,JavaScript .1.2 vv ,VBScript).

7. An cac Scripts oi vi cac Browser khong cung cap JavaScript:


<SCRIPT LANGUAGE=JavaScript> <!- - Dong dau Script oi vi cac Browser khong cung cap (support) JavaScript Program //Dong ket thuc viec dau Script va chu thch - - > </SCRIPT>

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 2

8. S dung tap tin JavaScript ben ngoai :


<SCRIPT LANGUAGE=JavaScript SRC=http://www.hcmuns.edu.vn/scroll.js> <!- - Dong dau Script oi vi cac Browser khong cung cap (support) JavaScript Program //Dong ket thuc viec dau Script va chu thch - - > </SCRIPT>

9. Them chng trnh vao tap tin HTML:


<HTML> <HEAD> <TITLE>Listing 2.1</TITLE> </HEAD> <BODY> Here is result: <SCRIPT LANGUAGE="Javascript"> <!-document.writeln("It work<BR>"); --> </SCRIPT> </BODY> </HTML>

Bai 2: S DUNG JAVASCRIPT


1. Cu phap c ban cua lenh :
JavaScript xay dng cac ham,cac phat bieu,cac toan t va cac bieu thc tren cung mot dong va ket thuc bang ; V du: document.writeln("It work<BR>");

2. Cac khoi lenh:

Nhieu dong lenh co the c lien ket vi nhau va c bao bi { V du: { document.writeln("Does It work"); document.writeln("It work!"); }

3. Xuat d lieu ra ca so trnh duyet:

Dung 2 phng phap document.write() va document.writeln() V du: document.write(Test); document.writeln(Test);

4. Xuat cac the HTML t JavaScript


JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 3

V du 1:
<HTML> <HEAD> <TITLE>Outputting Text</TITLE> </HEAD> <BODY> This is text plain <BR> <B> <SCRIPT LANGUAGE="Javascript"> <!- document.write("This is text bold </B>"); - -> </SCRIPT> </BODY> </HTML>

V du 2:
<HTML> <HEAD> <TITLE>Example 2.4 </TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!- document.write('<IMG SRC="welcome.gif">'); document.write("<BR><H1>WELCOME TO NETSCAPE 2.1</H1>"); - -> </SCRIPT> </BODY> </HTML>

5. S dung phng phap writeln() vi the PRE:


<HTML> <HEAD> <TITLE>Outputting Text</TITLE> </HEAD> <BODY> <PRE> <SCRIPT LANGUAGE="Javascript"> <!- document.writeln("One,"); document.writeln("Two,"); document.write("Three"); document.write("..."); - -> </SCRIPT> </PRE> </BODY> </HTML>

6. Cac k t ac biet trong chuoi:


\n : New line \t : Tab \r : carriage return \f : form feed \b: backspace V du: document.writeln("It work!\n");

7. Lam viec vi cac dialog boxes


S dung ham alert() e hien th thong bao trong mot hop. V du:
<HTML> <HEAD> <TITLE>Example 2.5 </TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!- alert("Welcome to Netscape Navigator 21"); document.write('<IMG SRC="welcome.gif">'); - -> </SCRIPT> </BODY>

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 4

8. Tng tac vi ngi s dung:


S dung phng phap promt() e tng tac vi ngi s dung. V du 1:
<HTML> <HEAD> <TITLE>Listing 2.6</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!- document.write("Your favorite color is:"); document.writeln(prompt("enter your favorite color:","Blue")); - -> </SCRIPT> </BODY> </HTML>

V du 2:
<HTML> <HEAD> <TITLE>Listing 2.6</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!- document.write('<IMG SRC="welcome.gif">'); document.write("<H1>Greeting ,"); document.writeln(prompt("enter your name:","name")); document.write("Welcome to netscape navigator 2.01 </H1>"); - -> </SCRIPT> </BODY> </HTML>

S dung dau + e cong 2 chuoi n lai: V du 3:


<HTML> <HEAD> <TITLE>Listing 2.6</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!- document.write('<IMG SRC="welcome.gif">'); document.write("<H1>Greeting ," + prompt("enter your name:","name") + " Welcome to netscape navigator 2.01 </H1>"); - -> </SCRIPT> </BODY> </HTML>

9. Cac kieu d lieu trong JavaScript:


a. D lieu kieu so: + So nguyen: v du 720 + So Octal: v du :056 + So Hexa:v du:0x5F + So thap phan :v du :7.24 , -34.2 ,2E3 b. D lieu kieu chuoi: v du: Hello 245 c. D lieu kieu Boolean: Ket qua tra ve la true hoac false.

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 5

d. D lieu kieu null: Tra ve gia tr rong. e. D lieu kieu van ban (giong nh kieu chuoi)

10. Tao bien trong JavaScript:


Var example; Var example=Hello; Ta co the dung document.write(example); e xuat noi dung cua bien. V du 1: dung t khoa var e khai bao bien
<HTML> <HEAD> <TITLE>Example 3.1</TITLE> <SCRIPT LANGUAGE="Javascript"> <!- var name=prompt("enter your name:","name"); - -> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!-document.write('<IMG SRC="Welcome.gif">'); document.write("<H1>Greeting ," + name + " Welcome to netscape navigator 2.01 </H1>"); --> </SCRIPT> </BODY> </HTML> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!-document.write('<IMG SRC="Welcome.gif">'); document.write("<H1>Greeting ," + name + " Welcome to netscape navigator 2.01 </H1>"); --> </SCRIPT> </BODY> </HTML>

V du 2: tao lai mot gia tr mi cho bien


<HTML> <HEAD> <TITLE>Example 3.2</TITLE> <SCRIPT LANGUAGE="Javascript"> var name=prompt("enter your name:","name"); alert ("greeting " + name + " , "); name=prompt("enter your friend's name:","friend's name"); </SCRIPT>

11. Lam viec vi bien va bieu thc:


Thiet lap bieu thc: Cu phap: <bien> <toan t > <bieu thc> * Toan t: = Thiet lap gia tr ben phai cho ben trai V du :x=5 += Cong trai va phai ,sau o gan ket qua cho ben trai phep toan V du: cho x=10,y=5 x+=y => x=15 -= Tr ben trai cho ben phai ,gan ket qua lai cho ben trai x-=y => x=5

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 6

*= Nhan ben trai cho ben phai,gan ket qua cho ben trai x*=y => x=50 /= Chia ben trai cho phai ,gan ket qua lai cho ben trai x/=y => x=2 %= Chia ben trai cho ben phai va lay so d gan lai cho ben trai x%=y => x=0 * Cac toan t khac: V du: x+=15+3 y=++x; (=> y=6 v x tang len 6) => x=18 z=x++; (=> z=6 v sau o x gan cho z) 8+5 sau o x tang 1 => x=7 32.5 * 72.3 Do o ta co ket qua cuoi cung la: 12 % 5 x=7;y=6;z=6; Dau ++ va dau - - va dau V du: x=5; V du: x=-x => x=-5 x=5; Phep toan Logic && : va ||: hoac ! not V du: x=5 ,y=2 ,c=3 (x>y) && (x>c) false && anything is always false (x>y) || (c<x) => true !x Toan t so sanh trong JavaScript: == 1==1 => true != 3<1 =>false > 5 >=4 =>true < the != he => true >= 4==4 =>true <= V du: Toan t ieu kien: Cu phap: (ieu kien ) ? gia tr 1 : gia tr 2 Neu ieu kien ung th tra ve gia tr 1 Neu ieu kien sai th tra ve gia tr 2 V du:
JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 7

(day=Saturday) ? Weekend : Not Saturday Toan t chuoi: Welcome to + Netscape Navigator V du: Var welcome=Welcome to Welcome += Netscape Navigator ! welcome= Welcome to Netsacpe Navigator V du : S dung toan t ieu kien e kiem tra ngo vao
<HTML> <HEAD> <TITLE>Example 3.3</TITLE> <SCRIPT LANGUAGE="Javascript"> var question="What is 10+10 ?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorect.gif">'; var response=prompt(question,"0"); var output = (response==answer) ? correct:incorrect; </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!-document.write(output); --> </SCRIPT> </BODY> </HTML>

12. Cau truc ieu kien if else if ieu kien lenh ; if ieu kien { Ma JavaScript } V du: if (day==Saturday) { document.writeln(Its the weekend); alert( Its the weekend); } V du: If (day==Saturday) { document.writeln(Its the weekend); }

If (day!=Saturday) { document.writeln(Its not Saturday); } S dung cau truc else if cho v du tren If (day==Saturday) { document.writeln(Its the weekend); } else { document.writeln(Its not Saturday); }

Cau truc ket hp : if ieu kien 1 { Cac lenh JavaScript

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 8

if ieu kien 2 { Cac lenh JavaScript } else { cac lenh khac } Cac lenh JavaScript } else { Cac lenh khac } V du 1 : S dung phng phap confirm() vi phat bieu if
<HTML> <HEAD> <TITLE>Example 3.3</TITLE> <SCRIPT LANGUAGE="Javascript"> var question="What is 10+10 ?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorect.gif">'; var response=prompt(question,"0"); if (response != answer) { if (confirm("Wrong ! press OK for a second change")) <HTML> <HEAD> <TITLE>Example 3.3</TITLE> <SCRIPT LANGUAGE="Javascript"> var question="What is 10+10 ?"; var answer=20; var correct='<IMG SRC="correct.gif">'; var incorrect='<IMG SRC="incorect.gif">'; var response=prompt(question,"0"); if (response != answer) { if (confirm("Wrong ! press OK for a second change")) response=prompt(question,"0"); }else { if (confirm("Correct ! press OK for a second question")) {
MTWRFSS

response=prompt(question,"0"); } var output = (response ==answer ) ? correct:incorrect ; </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!-document.write(output); --> </SCRIPT> </BODY> </HTML> question="What is 10*10"; answer=100; response=prompt(question,"0"); } } var output = (response ==answer ) ? correct:incorrect ; </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="Javascript"> <!-document.write(output); --> </SCRIPT> </BODY> </HTML>

V du 2 : S dung phng phap confirm() vi phat bieu if - else

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 9

BAI 3: HAM VA OI TNG


Trong ky thuat lap trnh cac lap trnh vien thng s dung ham e thc hien mot oan chng trnh the hien cho mot module nao o e thc hien mot cong viec nao o. Trong Javascript co cac ham c xay dng san e giup ban thc hien mot chc nang nao o v du nh ham alert(), document.write(), parseInt() va ban cung co the nh ngha ra cac ham khac cua mnh e thc hien mot cong viec nao o cua ban, e nh ngha ham ban theo cu phap sau: function function_name(parameters, arguments) { command block }

Truyen tham so:


function printName(name) { document.write(<HR>Your Name is <B><I>); document.write(name); document.write(</B></I><HR>); }

V du:
Goi ham printName()vi lenh sau printName(Bob); Khi ham printName()c thi hanh gia tr cua name la "Bob" neu goi ham printName()vi oi so la mot bien

var user = John; printName(user);


Khi o name la John. Neu ban muon thay oi gia tr cua name ban co the lam nh sau : name

= Mr. + name;

Pham vi cua bien:


Bien toan cuc (Global variable) Bien cuc bo (Local variable)

Tra ve cac gia tr:


V du: Dung return e tra ve gia tr cua bien cube. function cube(number) { var cube = number * number * number; return cube; }
MTWRFSS

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 10

V du:
MTWRFSS

<HTML> <HEAD> <TITLE>Example 4.1</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //DEFINE FUNCTION testQuestion() function testQuestion(question) { //DEFINE LOCAL VARIABLES FOR THE FUNCTION var answer=eval(question); var output=What is + question + ?; var correct=<IMG SRC=correct.gif>; var incorrect=<IMG SRC=incorrect.gif>; //ASK THE QUESTION var response=prompt(output,0");

//CHECK THE RESULT return (response == answer) ? correct : incorrect; } // STOP HIDING FROM OTHER BROWSERS -> </SCRIPT> </HEAD< <BODY> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //ASK QUESTION AND OUTPUT RESULTS var result=testQuestion(10 + 10); document.write(result); //STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML>

Ham eval dung chuyen oi gia tr chuoi so thanh gia tr so eval(10*10)tra ve gia tr la 100

Ham goi lai ham:


V du:
<HTML> <HEAD> <TITLE>Example 4.2</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //DEFINE FUNCTION testQuestion() function testQuestion(question) { //DEFINE LOCAL VARIABLES FOR THE FUNCTION var answer=eval(question); var output=What is + question + ?; var correct=<IMG SRC=correct.gif>; var incorrect=<IMG SRC=incorrect.gif>; //ASK THE QUESTION var response=prompt(output,0"); //CHECK THE RESULT return (response == answer) ? correct : testQuestion(question); } // STOP HIDING FROM OTHER BROWSERS -> </SCRIPT> </HEAD< <BODY> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //ASK QUESTION AND OUTPUT RESULTS var result=testQuestion(10 + 10); document.write(result); //STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML> //DEFINE LOCAL VARIABLES FOR THE FUNCTION var answer=eval(question); var output=What is + question + ?; var correct=<IMG SRC=correct.gif>;

V du 2:
<HTML> <HEAD> <TITLE>Example 4.2</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //DEFINE FUNCTION testQuestion() function testQuestion(question,chances) {

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 11

var incorrect=<IMG SRC=incorrect.gif>; 4 //ASK THE QUESTION var response=prompt(output,0"); //CHECK THE RESULT if (chances > 1) { return (response == answer) ? correct : testQuestion(question,chances-1); } else { return (response == answer) ? correct : incorrect; } }

// STOP HIDING FROM OTHER BROWSERS -> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //ASK QUESTION AND OUTPUT RESULTS var result=testQuestion(10 + 10,3); document.write(result); //STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </BODY> </HTML>

Bai 4: TAO OI TNG TRONG JAVASCRIPT


1. nh ngha thuoc tnh cua oi tng:
function student(name,age, grade) { this.name = name; this.age = age; this.grade = grade; } e tao mot Object ta s dung phat bieu new.V du e tao oi tng student1

student1 = new student(Bob,10,75);


3 thuoc tnh cua oi tng student1 la :

student1.name student1.age student1.grade


V du e tao oi tng student2 student2 = new student(Jane,9,82);

e them thuoc tnh cho student1 ban co the lam nh sau:


student1.mother = Susan; hoac ban co the nh ngha lai ham student
MTWRFSS

function student(name, age, grade, mother) { this.name = name; this.age = age; this.grade = grade; this.mother = mother; }

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 12

oi tng la thuoc tnh cua oi tng khac


V du: function grade (math, english, science) { this.math = math; this.english = english; this.science = science; } bobGrade = new grade(75,80,77); janeGrade = new grade(82,88,75); student1 = new student(Bob,10,bobGrade); student2 = new student(Jane,9,janeGrade); student1.grade.math:dung e lay iem Toan cua student1 student2.grade.science: dung lay iem mon Khoa hoc cua student2

2. Them phng phap cho oi tng:


function displayProfile() { document.write(Name: + this.name + <BR>); document.write(Age: + this.age + <BR>); document.write(Mothers Name: + this.mother + <BR>); document.write(Math Grade: + this.grade.math + <BR>); document.write(English Grade: + this.grade.english + <BR>); document.write(Science Grade: + this.grade.science + <BR>); }

function student(name,age, grade) { this.name = name; this.age = age; this.grade = grade; this.mother = mother; this.displayProfile = displayProfile; } student1.displayProfile();

V du:

4
<HTML> <HEAD> <TITLE>Example 4.3</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS //DEFINE METHOD function displayInfo() { document.write(<H1>Employee Profile: + this.name + </H1><HR><PRE>); document.writeln(Employee Number: + this.number);

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 13

document.writeln(Social Security Number: + this.socsec); document.writeln(Annual Salary: + this.salary); document.write(</PRE>); } //DEFINE OBJECT function employee() { this.name=prompt(Enter Employees Name,Name); this.number=prompt(Enter Employee Number for + this.name,000-000"); this.socsec=prompt(Enter Social Security Number for + this.name,000-00-0000"); this.salary=prompt(Enter Annual Salary for + this.name,$00,000"); this.displayInfo=displayInfo; } newEmployee=new employee();

// STOP HIDING FROM OTHER BROWSERS -> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS newEmployee.displayInfo(); // STOP HIDING FROM OTHER BROWSERS -> </SCRIPT> </BODY> </HTML>

Vi du:
<script LANGUAGE="JavaScript"> <!-- Begin var day=""; var month=""; var ampm=""; var ampmhour=""; var myweekday=""; var year=""; mydate = new Date(); myday = mydate.getDay(); mymonth = mydate.getMonth(); myweekday= mydate.getDate(); weekday= myweekday; myyear= mydate.getYear(); year = myyear; JAVASCRIPT myhours = mydate.getHours(); ampmhour = (myhours > 12) ? myhours 12 : myhours; ampm = (myhours >= 12) ? 'Buo i Chie u ' : ' Buo i Sa ng '; mytime = mydate.getMinutes(); myminutes = ((mytime < 10) ? ':0' : ':') + mytime; if(myday == 0) day = " Chu Nha t , "; else if(myday == 1) day = " Th hai, "; else if(myday == 2) day = " Th ba, "; else if(myday == 3) PAGE: 14

MEDIASPACE CLUB (HTD)

day = " Th t, "; else if(myday == 4) day = " Th na m, "; else if(myday == 5) day = " Th sa u , "; else if(myday == 6) day = " Th ba y , "; if(mymonth == 0) { month = "tha ng mo t ";} else if(mymonth ==1) month = "tha ng hai "; else if(mymonth ==2) month = "tha ng ba "; else if(mymonth ==3) month = "tha ng t "; else if(mymonth ==4) month = "tha ng na m, ";

else if(mymonth ==5) month = "tha ng sa u "; else if(mymonth ==6) month = "tha ng ba y "; else if(mymonth ==7) month = "tha ng ta m "; else if(mymonth ==8) month = "tha ng chn "; else if(mymonth ==9) month = "tha ng m i "; else if(mymonth ==10) month = "tha ng m i mo t "; else if(mymonth ==11) month = "tha ng m i hai "; // End --> </script>

Trong phan body ban co the xuat ra dang nh sau:

<body> <script> document.write("<b><font color=#0000ff face='VNITimes,helvetica,arial'>" + ampmhour + "" + myminutes + ampm) document.write(" - " + day + " nga y " + myweekday +" "); document.write( month + " , na m " + year + "</font>"); </script>

</body>

Bai 5: S KIEN TRONG JAVASCRIPT


Cac s kien cung cap cac tng tac vi ca so trnh duyet va tai lieu hien hanh ang c load trong trang web, cac hanh ong cua user khi nhap d lieu vao form va khi click vao cac button trong form. Khi s dung bo quan ly s kien ban co the viet cac ham e bieu dien cho cac hanh ong da vao cac s kien oc chon

Bang s kien trong Javascript


JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 15

Ten s kien blur

click change focus load mouseover select submit unload

Mo ta Xay ra khi iem tap trungcua ngo vao c di chuyen ra khoi mot thanh phan cua Form (Khi user click ra ngoai mot trng) Khi user Click vao 1 link hoac thanh phan cua Form. Xay ra khi gia tr cua Form Field b thay oi bi user. Xay ra khi ngo vao tap trung vao thanh phan cua Form Xay ra khi mot trang c Load vao trong bo duyet. Xay ra khi User di chuyen mouse qua mot Hyperlink. Xay ra khi User chon 1 trng cua thanh phan Form. Xay ra khi User xac nhan a nhap xong d lieu. Xay ra khi User ri khoi trang Web.

Bo quan ly s kien (Event Handler)


e quan ly cac s kien trong javascript ta dung cac bo quan ly s kien. Cu phap cua mot bo quan ly s kien:

<HTML_TAG OTHER_ATTRIBUTES eventHandler=JavaScript Program> V du: <INPUT TYPE=text onChange=checkField(this)> V du: <INPUT TYPE=text onChange= if (parseInt(this.value) <= 5) { alert(Please enter a number greater than 5.); } > V du: <INPUT TYPE=text onChange= alert(Thanks for the entry.); confirm(Do you want to continue?); > T khoa this: quy cho oi tng hien hanh.Trong Javascript Form la mo oi tng.Cac thanh phan cua Form bao gom text fields, checkboxes, radio buttons, buttons, va selection lists. V du: <INPUT TYPE=text onChange=checkField(this)>

Cac bo quan ly s kien trong Javascript


oi tng Bo quan ly s kien tng ng.

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 16

Selection list Text element Textarea element Button element Checkbox Radio button Hypertext link Reset button Submit button Document Window Form

onBlur, onChange, onFocus onBlur, onChange, onFocus, onSelect onBlur, onChange, onFocus, onSelect OnClick onClick OnClick onClick, onMouseOver OnClick OnClick

onLoad, onUnload onLoad, onUnload onSubmit

5 Cach dung bo quan ly s kien onLoad & onUnload


<HTML> <HEAD> <TITLE>Example 5.1</TITLE> </HEAD> <BODY onLoad=alert(Welcome to my page!); onUnload=alert(Goodbye! Sorry to see you go!);> <IMG SRC=title.gif> </BODY> </HTML>
MTWRFSS

Vi du:
<HTML> <HEAD> <TITLE>Example 5.1</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS var name = ; // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY onLoad= name = prompt(Enter Your Name:,Name); alert(Greetings + name + , welcome to my page!); onUnload= alert(Goodbye + name + , sorry to see you go!);> <IMG SRC=title.gif> </BODY> </HTML>

Vi du
MTWRFSS <HTML> <HEAD>

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 17

<TITLE>Example 5.1</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS // DEFINE GLOBAL VARIABLE var name = ; function hello() { name = prompt(Enter Your Name:,Name); alert(Greetings + name + , welcome to my page!); } function goodbye() { alert(Goodbye + name + , sorry to see you go!); } // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY onLoad=hello(); onUnload=goodbye();> <IMG SRC=title.gif> </BODY> </HTML>

Cac s kien va Form


Cac s kien c s dung e truy xuat Form nh: OnClick, onSubmit, onFocus, onBlur, va onChange. V du:

<INPUT TYPE=text NAME=test VALUE=test onBlur=alert(Thank You!); onChange=check(this);> Khi gia tr thay oi function check() se c goi. Ta dung t khoa this e chuyen oi tng cua trng hien hanh en ham check() Ban cung co the da vao cac phng phap va cac thuoc tnh cua oi tng bang phat bieu sau: this.methodName() & this.propertyName.
V du:
<HTML> <HEAD> <TITLE>Example 5.3</TITLE> <SCRIPT LANGUAGE=JavaScript> <!-- HIDE FROM OTHER BROWSERS function calculate(form) { form.results.value = eval(form.entry.value); } function getExpression(form) { form.entry.blur(); form.entry.value = prompt(Please enter a JavaScript mathematical expression,); calculate(form); } //STOP HIDING FROM OTHER BROWSERS --> </SCRIPT> </HEAD> <BODY> <FORM METHOD=POST> Enter a JavaScript mathematical expression: <INPUT TYPE=text NAME=entry VALUE= onFocus=getExpression(this.form);> <BR>

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 18

The result of this expression is: <INPUT TYPE=text NAME=results VALUE= onFocus=this.blur();>

</FORM> </BODY> </HTML>

MTWRFSS

formObjectName.fieldname:Dung e ch ten trng cua hien hanh trong Form. formObjectName.fieldname.value: dung lay gia tr cua trng form hien hanh. S dung vong lap trong JavaScript 1 . Vong lap for : Cu phap : for ( init value ; condition ; update expression ) V du : for (i = 0 ; i < 5 ; i++) { lenh ; } V du:
<HTML> <HEAD> <TITLE> for loop Examle </TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!- var name=prompt("What is your name?" ,"name"); var query= " " ; document.write("<H1>" + name + " 's 10 favorite foods </H1> "); for (var i=1 ;i<=10;i++) {

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 19

document.write(i + " " + prompt('Enter food number ' + i, 'food' ) + '<BR>'); } - -> </SCRIPT> </BODY> </HTML>

2 . Vong lap while : Cu phap: While ( ieu kien) { lenh JavaScript ; } V du: var num=1; while(num<=10) { document.writeln(num); num++; } V du: var answer= ; var correc=100; var question= what is 10*10 ? ; while(answer!=correct) { answer=prompt(question,0); } 3. Tao mang vi vong lap for: function createArray(num) { this.length=num; for ( var j=0 ; j<num; j++) this[j]=0; } Ham se tao mot mang co gia tr index bat au la 0 va gan tat ca cac gia tr cua mang ve 0 . e s dung oi tng mang ta co the lam nh sau: newArray= new createArray(4) Se tao ra mot mang gom 4 thanh phan newArray[0] NewArray[3]

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 20

S dung oi tng Windows Window la oi tng cua moi trng Navigator,ngoai cac thuoc tnh Window oi tng window con gi cac oi tng khac ma co the c xem nh la cac thanh phan (member) cua window, cac oi tng o la: Cac frame a c tao Cac oi tng location va histtory oi tng document oi tng document cha (encompasses) tat ca cac thanh phan trong trang HTML.ay la mot oi tng hoan hao co cac oi tng khac cua JavaScript gan (attached) vao no (nh la anchor,form,history,link).Hau nh moi chng trnh JavaScript eu co s dung oi tng nay e tham khao en cac thanh phan trong trang HTML. 1) Cac thuoc tnh (properties) cua oi tng document a . alink b . anchor c . bgColor d . cookies e . fgColor f . form g . lastModified h . linkColor i . links j . location k . referrer l . title m . vlinkColor 2) Cac hanh vi (Methods) cua oi tng document a . clear() b . close() c . open() d . write() e . writeln() 3) Cac thuoc tnh cua oi tng Window a . defaultStatus : Gia tr mat nhien c hien th thanh trang thai b . frames : Mang cac oi tng cha ng mot muc cho moi frame con trong mot frame tai lieu c . parent : c s dung trong FRAMSET d . self : Ca so hien hanh , dung e phan biet gia cac ca so hien hanh va cac forms co cung ten . e . status : Gia tr cua chuoi van ban c hien th tai thanh status bar.Dung e hien thi cac thong bao cho ngi s dung . f . top : nh cao nhat cua ca so cha
JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 21

g. 4) a. b. c.

window Cac hanh vi (Methods) cua oi tng window alert() : Hien 1 thong bao trong hop thoai vi OK button. close() : ong ca so hien hanh. open() : M mot ca so mi vi 1 tai lieu c ch ra hoac m mot tai lieu trong mot ten ca so c ch nh. d . prompt() : Hien mot hop thong bao e . setTimeout() : f . clearTimeout() : Hanh vi nay cung cap cach goi phat bieu JavaScript sau mot khoang thi gian troi qua .Ngoai ra oi tng window co the thc hien event handler : onLoad=statement Lam viec vi status bar Khi user di chuyen qua mot hyperlink ta co the hien ra mot thong bao tai thanh status bar cua bowser da vao event handler onMouseOver va bang cach at self.status la mot chuoi (hoac window.status). V du:
<HTML> <HEAD> <TITLE>Status Example</TITLE> <BODY> <A HREF=plc.htm onMouseOver=self.status=Chuyen de PLC ;return true ; >Lop chuyen de PLC </A> <A HREF=tkweb.htm onMouseOver=self.status=Thiet Ke Trang Web ;return true ; >Thiet Ke Web</A> </BODY> </HTML>

M va ong cac ca so S dung phng phap open() va close() ta co the ieu khien viec m va ong ca so cha tai lieu. open (URL , WindowName , featureList) ; Cac ac iem trong phng phap open() gom co: toolbar : tao mot toolbar chuan location: tao mot vung location directories: tao cac button th muc chuan status: tao thanh trang thai. menubar : tao thanh menu tai nh cua ca so scrollbars: tao thanh scroll bar resizable: cho phep user thay oi kch thc ca so width : ch nh chieu rong ca so theo n v pixel height : ch nh chieu cao ca so theo n v pixel V du: window.open( plc.htm,newWindow,toolbar=yes,location=1,directories=yes,status=yes,

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 22

menubar=1,scroolbar=yes,resizable=0,copyhistory=1,width=200,height=200); V du:
<HTML> <HEAD> <TITLE>WINDOWS</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-function openWindow(url,name) { popupWin = window.open(url, name, "scrollbars=yes,width=800, heigth=200 "); } --> </SCRIPT> </HEAD> <BODY> <a href="javascript:openWindow('../chuyende/plc.htm','Win')">PLC</a>, <a href="javascript:openWindow('../chuyende/suachuaw.htm','stoogeWin')">Sua chua</a>, <a href="javascript:openWindow('../chuyende/tkweb.htm','stoogeWin')">Thiet ke web</a> </BODY> </HTML>

e ong ca so ta co the dung phng phap close() V du:


<HTML> <HEAD> <TITLE>Close Example</TITLE> </HEAD> <BODY > <A HREF="#" ONCLICK="self.close();return false"><IMG ALIGN="middle" SRC="../demo.gif" WIDTH="16" HEIGHT="16" BORDER="0"></A> <A HREF="#" ONCLICK="self.close();return false">Close This Sample</A> </BODY > </HTML>

S dung oi tng string String la mot oi tng cua JavaScript,khi dung oi tng string chung ta khong can cac phat bieu e tao mot instance (the nghiem) cua oi tng ,bat ky luc nao ta at text gia hai dau ngoac kep va gan no en mot bien hoac mot thuoc tnh th ta a tao mot oi tng string. 1. Cac thuoc tnh cua oi tng string Thuoc tnh length gi so k t cua string. 2. Cac hanh vi (Methods) cua oi tng string a . Anchor (nameAttribute) b . big() c . blink() d . bold() e . charAt(index) f . fixed() g . fontcolor(color)
JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 23

h . fontsize(size) i . indexOf(character,[fromIndex]) j . italics() k . lastIndexOf(character,[fromIndex]) l . link(URL) m . small() n . strike() o . sub() p . substring(startIndex,endIndex) q . sup() r . toLowerCase() s . toUpperCase()

----------------------------

Bien soan: Pham phu Tai Huu Thanh Design

JAVASCRIPT

MEDIASPACE CLUB (HTD)

PAGE: 24

You might also like