Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

JAVASCRIPT

Bai 1: TONG QUAN VE JAVASCRIPT.

1. ac tnh cua ngon ng Javascript:

J 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 Mo ta
Window 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 Cung cap cac tnh chat va phng phap lam viec vi cac a ch
URL hien hanh c m.
History Cac oi tng history cung cap thong tin ve cac danh sach cu va
co the gii han s tng tac vi danh sach.
Document 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> <SCRIPT LANGUAGE="Javascript">
<HEAD> <!- -
<TITLE>Outputting Text</TITLE> document.write("This is text bold </B>");
</HEAD> - ->
<BODY> </SCRIPT>
This is text plain <BR> </BODY>
<B> </HTML>

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

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


<HTML> document.writeln("Two,");
<HEAD> document.write("Three");
<TITLE>Outputting Text</TITLE> document.write("...");
</HEAD> - ->
<BODY> </SCRIPT>
<PRE> </PRE>
<SCRIPT LANGUAGE="Javascript"> </BODY>
<!- - </HTML>
document.writeln("One,");
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> alert("Welcome to Netscape Navigator
<HEAD> 21");
<TITLE>Example 2.5 </TITLE> document.write('<IMG
</HEAD> SRC="welcome.gif">');
<BODY> - ->
<SCRIPT LANGUAGE="Javascript"> </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> document.write("Your favorite color
<HEAD> is:");
<TITLE>Listing 2.6</TITLE> document.writeln(prompt("enter your
</HEAD> favorite color:","Blue"));
<BODY> - ->
<SCRIPT LANGUAGE="Javascript"> </SCRIPT>
<!- - </BODY>
</HTML>

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

S dung dau + e cong 2 chuoi n lai:


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

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> <BODY>
<HEAD> <SCRIPT LANGUAGE="Javascript">
<TITLE>Example 3.1</TITLE> <!--
document.write('<IMG
<SCRIPT LANGUAGE="Javascript"> SRC="Welcome.gif">');
<!- - document.write("<H1>Greeting ," +
var name=prompt("enter your name + " Welcome to netscape
name:","name"); navigator 2.01 </H1>");
- -> -->
</SCRIPT> </SCRIPT>
</BODY>
</HEAD> </HTML>
V du 2: tao lai mot gia tr mi cho bien
<HTML> </HEAD>
<HEAD> <BODY>
<TITLE>Example 3.2</TITLE> <SCRIPT LANGUAGE="Javascript">
<!--
<SCRIPT LANGUAGE="Javascript"> document.write('<IMG
var name=prompt("enter your SRC="Welcome.gif">');
name:","name"); document.write("<H1>Greeting ," +
alert ("greeting " + name + " , "); name + " Welcome to netscape
name=prompt("enter your friend's navigator 2.01 </H1>");
name:","friend's name"); -->
</SCRIPT>
</SCRIPT> </BODY>
</HTML>

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> var output = (response==answer) ?
<HEAD> correct:incorrect;
<TITLE>Example 3.3</TITLE> </SCRIPT>
</HEAD>
<SCRIPT LANGUAGE="Javascript">
var question="What is 10+10 ?"; <BODY>
var answer=20; <SCRIPT LANGUAGE="Javascript">
var correct='<IMG <!--
SRC="correct.gif">'; document.write(output);
var incorrect='<IMG -->
SRC="incorect.gif">'; </SCRIPT>
var response=prompt(question,"0"); </BODY>
</HTML>

12. Cau truc ieu kien if else


if ieu kien
lenh ;

if ieu kien {
Ma JavaScript
}
V du: If (day!=Saturday) {
if (day==Saturday) { document.writeln(Its not Saturday);
document.writeln(Its the weekend); }
alert( Its the weekend); S dung cau truc else if cho v du tren
} If (day==Saturday) {
V du: document.writeln(Its the weekend);
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> response=prompt(question,"0");
<HEAD> }
<TITLE>Example 3.3</TITLE>
var output = (response ==answer ) ?
<SCRIPT LANGUAGE="Javascript"> correct:incorrect ;
var question="What is 10+10 ?";
var answer=20; </SCRIPT>
var correct='<IMG
SRC="correct.gif">'; </HEAD>
var incorrect='<IMG <BODY>
SRC="incorect.gif">'; <SCRIPT LANGUAGE="Javascript">
<!--
var response=prompt(question,"0"); document.write(output);
-->
if (response != answer) { </SCRIPT>
if (confirm("Wrong ! press OK for </BODY>
a second change")) </HTML>
V du 2 : S dung phng phap confirm() vi phat bieu if - else
<HTML> question="What is 10*10";
<HEAD> answer=100;
<TITLE>Example 3.3</TITLE>
response=prompt(question,"0");
<SCRIPT LANGUAGE="Javascript"> }
var question="What is 10+10 ?"; }
var answer=20;
var correct='<IMG var output = (response ==answer ) ?
SRC="correct.gif">'; correct:incorrect ;
var incorrect='<IMG
SRC="incorect.gif">'; </SCRIPT>

var response=prompt(question,"0"); </HEAD>


<BODY>
if (response != answer) { <SCRIPT LANGUAGE="Javascript">
if (confirm("Wrong ! press OK for <!--
a second change")) document.write(output);
response=prompt(question,"0"); -->
}else { </SCRIPT>
if (confirm("Correct ! press OK </BODY>
for a second question")) </HTML>
MTWRFSS
{

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

function cube(number) {
var cube = number * number * number;
return cube;
}

JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 10


V du:
MTWRFSS

<HTML> //CHECK THE RESULT


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

JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 11


var incorrect=<IMG // STOP HIDING FROM OTHER BROWSERS --
SRC=incorrect.gif>; >
4 </SCRIPT>
//ASK THE QUESTION </HEAD>
var response=prompt(output,0"); <BODY>
//CHECK THE RESULT <SCRIPT LANGUAGE=JavaScript>
if (chances > 1) { <!-- HIDE FROM OTHER BROWSERS
return (response == answer) ? correct //ASK QUESTION AND OUTPUT RESULTS
: testQuestion(question,chances-1); var result=testQuestion(10 + 10,3);
} else { document.write(result);
return (response == answer) ? correct //STOP HIDING FROM OTHER BROWSERS -->
: incorrect; </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

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

JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 13


document.writeln(Social Security // STOP HIDING FROM OTHER BROWSERS --
Number: + this.socsec); >
document.writeln(Annual Salary: + </SCRIPT>
this.salary); </HEAD>
document.write(</PRE>); <BODY>
} <SCRIPT LANGUAGE=JavaScript>
//DEFINE OBJECT <!-- HIDE FROM OTHER BROWSERS
function employee() { newEmployee.displayInfo();
this.name=prompt(Enter Employees // STOP HIDING FROM OTHER BROWSERS --
Name,Name); >
this.number=prompt(Enter Employee </SCRIPT>
Number for + this.name,000-000"); </BODY>
this.socsec=prompt(Enter Social </HTML>
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();

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

JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 14


day = " Th t, "; else if(mymonth ==5)
else if(myday == 4) month = "tha ng sa u ";
day = " Th na m, "; else if(mymonth ==6)
else if(myday == 5) month = "tha ng ba y ";
day = " Th sa u , "; else if(mymonth ==7)
else if(myday == 6) month = "tha ng ta m ";
day = " Th ba y , "; else if(mymonth ==8)
if(mymonth == 0) { month = "tha ng chn ";
month = "tha ng mo t ";} else if(mymonth ==9)
else if(mymonth ==1) month = "tha ng m i ";
month = "tha ng hai "; else if(mymonth ==10)
else if(mymonth ==2) month = "tha ng m i mo t ";
month = "tha ng ba "; else if(mymonth ==11)
else if(mymonth ==3) month = "tha ng m i hai ";
month = "tha ng t "; // End -->
else if(mymonth ==4) </script>
month = "tha ng na m, ";

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

<body>

<script>
document.write("<b><font color=#0000ff face='VNI-
Times,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 Mo ta
blur 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)
click Khi user Click vao 1 link hoac thanh phan cua Form.
change Xay ra khi gia tr cua Form Field b thay oi bi user.
focus Xay ra khi ngo vao tap trung vao thanh phan cua Form
load Xay ra khi mot trang c Load vao trong bo duyet.
mouseover Xay ra khi User di chuyen mouse qua mot Hyperlink.
select Xay ra khi User chon 1 trng cua thanh phan Form.
submit Xay ra khi User xac nhan a nhap xong d lieu.
unload 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 onBlur, onChange, onFocus
Text element onBlur, onChange, onFocus, onSelect
Textarea element onBlur, onChange, onFocus, onSelect
Button element OnClick
Checkbox onClick
Radio button OnClick
Hypertext link onClick, onMouseOver
Reset button OnClick
Submit button OnClick
Document onLoad, onUnload
Window onLoad, onUnload
Form 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> expression,);
<HEAD> calculate(form);
<TITLE>Example 5.3</TITLE> }
//STOP HIDING FROM OTHER BROWSERS -->
<SCRIPT LANGUAGE=JavaScript> </SCRIPT>
<!-- HIDE FROM OTHER BROWSERS </HEAD>
function calculate(form) { <BODY>
form.results.value = <FORM METHOD=POST>
eval(form.entry.value); Enter a JavaScript mathematical
} expression:
function getExpression(form) { <INPUT TYPE=text NAME=entry
form.entry.blur(); VALUE=
form.entry.value = prompt(Please onFocus=getExpression(this.form);>
enter a JavaScript mathematical <BR>

JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 18


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

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. window
4) Cac hanh vi (Methods) cua oi tng window
a. alert() : Hien 1 thong bao trong hop thoai vi OK button.
b. close() : ong ca so hien hanh.
c. 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