Professional Documents
Culture Documents
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.
JAVASCRIPT
PAGE: 1
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.
JAVASCRIPT
PAGE: 2
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!"); }
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>
JAVASCRIPT
PAGE: 4
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>
JAVASCRIPT
PAGE: 5
d. D lieu kieu null: Tra ve gia tr rong. e. D lieu kieu van ban (giong nh kieu chuoi)
JAVASCRIPT
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); }
JAVASCRIPT
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>
JAVASCRIPT
PAGE: 9
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
= Mr. + name;
JAVASCRIPT
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
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
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>
function student(name, age, grade, mother) { this.name = name; this.age = age; this.grade = grade; this.mother = mother; }
JAVASCRIPT
PAGE: 12
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
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
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>
<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>
PAGE: 15
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.
<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)>
JAVASCRIPT
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
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
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>
<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
PAGE: 18
The result of this expression is: <INPUT TYPE=text NAME=results VALUE= 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
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
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
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>
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()
----------------------------
JAVASCRIPT
PAGE: 24