You are on page 1of 114

● Gi i thi u v Javascript

● Nhúng Javascript vào trang web


● Cú pháp và ki u d li u Javascript
● X lý s ki n
● DOM HTML v i Javascript
● Ví d

ể ứ ụ 1
ể ứ ụ 2

ể ứ ụ 3

● Client Side Script:


o
o

o
● Server Side Script:
o
o

ể ứ ụ 4







ể ứ ụ 5




o


o

o
o
o
ể ứ ụ 6
● Client-Side Script:
o Script đ c th c thi t i Client-Side (trình duy t): th c hi n các t ng tác v i ng i dùng
(t o menu chuy n đ ng, … ) , ki m tra d li u nh p, …
● Server-Side Script:
o Script đ c x lý t i Server-Side: nh m t o các trang web có kh năng phát sinh n i
dung đ ng. M t s x lý chính: k t n i CSDL, truy c p h th ng file trên server, phát sinh
n i dung html tr v ng i dùng…
● Khi trình duy t (Client browser) truy c p trang web có ch a các đo n mã x lý t i
server-side. Server (run-time engine) sẽ th c hiên
̣ cać lên
̣ h Server-side Scripts
và trả v n i dung HTML cho trình duy t.
● N i dung html tr v ch y u bao g m: mã html, client-script.

ể ứ ụ 7

ể ứ ụ 8
Java JavaScript

Java là ngôn ngữ lập trình tĩnh, hướng JavaScript là ngôn ngữ lập trình động (hay
đối tượng, hoạt động trên nhiều nền ngôn ngữ kịch bản - scripted language) được
tảng. sử dụng để làm cho các trang web trở nên sinh
động
JavaScript là ngôn ngữ được diễn giải/thông
Java là ngôn ngữ được biên dịch dịch (interpreted).
(compiled)
JavaScript phụ thuộc nhiều hơn, nghĩa là nó
Java là một ngôn ngữ độc lập hoạt động với HTML và CSS trên các trang web
để tạo nội dung động.

ể ứ ụ 9

o


o

ể ứ ụ 10
● S d ng th SCRIPT:
<script>
JavaScript statements;
</script>
● S d ng m t file JavaScript ngoài
<script src="filename.js"></script>

ể ứ ụ 11
<html>
<head>
<script>
some statements
</script>
</head>
<body>
<script>
some statements
</script>
<script src=“Tên_file_script.js">method()</script>
<script>
//gọi thực hiện các phương thức được định nghĩa
//trong “Tên_file_script.js”
</script>
</body>
</html>

ể ứ ụ 12
● thực thi web được
mở
● thực thi sau
đoạn script
● không hạn chế.

ể ứ ụ 13
<!DOCTYPE html>
<html>
<head>
<title>First page Javascript</title>
<script>
document.writeln("<H2>Hello JavaScript</H2>")
document.write("HelloWorld");
</script>
</head>
<body>
</body>
</html>

ể ứ ụ 14
ể ứ ụ 15

ể ứ ụ 16
● {}
● ;

o
o

ể ứ ụ 17
● Phân biệt
o

o

o
• var count=10, amount;
o
ể ứ ụ 18
Kiểu dữ liệu Ví dụ Mô tả
Object var listBooks = new Array(10) ; Trước khi sử dụng, phải cấp phát bằng từ
khóa new
String “The cow jumped over the moon.” Chứa được chuỗi unicode
“40” Chuỗi rỗng “”
Number 0.066218 Theo chuẩn IEEE 754
12
boolean true / false
undefined var myVariable ; myVariable = undefined
null connection.Close(); connection = null

ể ứ ụ 19

o “ ”
Kết quả:

ể ứ ụ 20
ể ứ ụ 21
ể ứ ụ 22

var a = null;
console.log(a); //null

ể ứ ụ 23

ể ứ ụ 24

ể ứ ụ 25

ể ứ ụ 26
● Bi n t đ i ki u d li u khi giá tr mà nó l u tr thay đ i
o Ví d :
var x = 10; // x kiểu Number
x = hello world ! ; // x kiểu String
● Có th c ng 2 bi n khác ki u d li u
o Ví d :
var x;
x = 12 + 34.5; // KQ: x = 1234.5
● Hàm : Đ i ki u d li u t chu i sang s .

ể ứ ụ 27
● kiểu số nguyên kiểu số
thực.
o

ể ứ ụ 28
null == undefined; // true
null === undefined; // false

NaN == NaN // false


NaN === NaN // false

ể ứ ụ 29
● Các ký t đ c n m gi a 2 nháy đ n.
o Ví d :
● Ngoài ra còn có các ký t đ c bi t sau đây:

● Các phép toán trên ký t : +, += (c ng 2 ký t )


● Phép toán so sánh : >, >=, < , <=, ==, !=

ể ứ ụ 30

o var chuoi = “Đây là kiểu Chuỗi”;


o
o

ể ứ ụ 31
● M t bi n có ki u lu n lý t n t i 1 trong 2 tr ng thái :
o Ví d :
● Các phép toán trên ki u lu n lý
o Phép so sánh : <, <=, >, >=, ==, !=
o Phép logic : && (và), || (ho c), ! (ph đ nh).

ể ứ ụ 32
<script>
var x = 10;
var y = 5;
document.write("The value of x is " + x + "
The value of y is " + y +"<br>");
document.write("x AND y = " + (x &&
y)+"<br>");
document.write("x OR y = " + (x || y)+"<br>");
document.write("NOT x = " + (!x)+"<br>");
</script>

ể ứ ụ 33
● Mảng một chiều:
o var A = new Array(10)
o
A[i]
● Mảng hai chiều
o

ể ứ ụ 34

o if
o if….. else
o Switch

ể ứ ụ 35
● Dùng đ x lý l nh khi bi u th c c a if tr v giá tr true
if (biểu thức điều kiện)
Khối lệnh;
● Ví d :
a= “mon”;
if (a==“tue”)
document.write(“Hôm nay được nghỉ”);

ể ứ ụ 36
if (biểu thức điều kiện)
Khối lệnh 1;
else
Khối lệnh 2;
● Ví d :
a=5;
if (a%2==0)
document.write(a, “là số chẵn”);
else
document.write(a, “là số lẻ”);

ể ứ ụ 37
switch (biến hoặc biểu thức)
{
case giá trị 1:
Khối lệnh 1;
break;
case giá trị 2:
Khối lệnh 2;
break;

default:
Khối lệnh n;
}

ể ứ ụ 38
var diem = “G”;
switch (diem) {
case “Y”:
document.write(“Yếu");
break;
case “TB”:
document.write(“Trung bình");
break;
case “K”:
document.write(“Khá");
break;
case “G” :
document.write(“Giỏi");
break;
default:
document.write(“Xuất sắc")
}

ể ứ ụ 39
● C u trúc đi u khi n l p trong ch ng trình là các l nh l p
● Các ki u l nh l p bao g m:
o
o
o

ể ứ ụ 40
for (biểu thức1; biểu thức 2; biểu thức3){
Khối lệnh;
}
o Biểu thức 1: khởi tạo giá trị
o Biểu thức 2: điều kiện
o Biểu thức 3: cập nhật giá trị
● Kh i l nh đ c th c hi n khi bi u th c 2 còn đúng.

● Ví d : for (i = 0; i < 10; i++)


s+=2*i;

ể ứ ụ 41
while (biểu thức điều kiện){
Khối lệnh;
}
● Kh i l nh đ c th c hi n khi bi u th c trong while còn đúng.
● Ví d :
i=0;
while (i<20){
s+=i;
i++;
}

ể ứ ụ 42
● Dùng t khóa đ khai báo hàm. Mu n tr v giá tr c a hàm ta dùng t
khoá .
● D ng th c khai báo chung:
function Tên_hàm(thamso1, thamso2,..)
{
Khối lệnh;
}
● Hàm có giá tr tr v :
function Tên_hàm(thamso1, thamso2,..)
{
Khối lệnh;
return (value);
}
ể ứ ụ 43
function Add(x,y)
{
return(x+y);
}
var t;
t = Add(4,8);
document.write(t);

ể ứ ụ 44
● Bi n chu i thành bi u th c
● Bi n chu i thành l nh
● Bi u th c có th bao g m nhi u bi n và nhi u thu c tính c a m t đ i t ng.
var x = 5;
var y = 10;
document.write(eval(“x+y+5”));

ể ứ ụ 45
<script>
eval("x=10;y=20;document.write(x*y)");
document.write("<br>" + eval("2+2"));
document.write("<br>" + eval(x+17));
</script>

<script>
var string= “10+ Math.sqrt(64)”;
document.write(string + “=”+ eval(string));
</script>

ể ứ ụ 46
(Điều kiện) ? value1: value2

<script>
var exp = 1;
var salary = exp > 3 ? 1000 : 500;
console.log(salary) //500
</script>

ể ứ ụ 47
<script>
var exp = 2;
var salary = exp < 1 ? 1000 :
exp < 2 ? 1500 :
exp < 3 ? 2000: 3000;
console.log(salary) //2000
</script>

ể ứ ụ 48
a ?? b

let a = NULL
console.log(a??50) //50
console.log(a) //NULL
let a=10
let c=30
console.log(a??b??c??d) //10
ể ứ ụ 49
a ??= b a ??(a=b)

let a = NULL
console.log(a??=50) //50
console.log(a) //50

ể ứ ụ 50
● L pđ it ng là t p các đ i t ng có cùng thu c tính và hành vi (ph ng th c)
● Thu c tính (bi n) dùng đ đ nh nghĩa đ i t ng.
● Ph ng th c (hàm): nh ng ho t đ ng c a l p đ i t ng

ể ứ ụ 51

objectName.propertyName

objectName.method()

● obj ?. prop

ể ứ ụ 52

o
o

o

ể ứ ụ 53
● Giá tr c a nó ch ra đ i t ng hi n hành và có th có các thu c tính chu n, ch ng
h n nh tên, đ dài, và giá tr đ c áp d ng phù h p
<script>
function person(first_name, last_name, age, sex){
this.first_name=first_name;
this.last_name=last_name;
this.age=age;
this.sex=sex;
this.printStats=printStats;
}
function printStats(){
document.write("Name :" + this.last_name + " " + this.first_name + "<br>" );
document.write("Age :"+this.age+"<br>");
document.write("Sex :"+this.sex+"<br>");
}
ể ứ ụ 54
person1= new person("Thuy", "Dau Bich", "23", "Female");
person2= new person("Chung", "Nguyen Bao", "24", "Male");
person3= new person("Binh", "Nguyen Nhat", "24", "Male");
person4= new person("Hoan", "Do Van", "23", "Male");
person1.printStats();
person2.printStats();
person3.printStats();
person4.printStats();
</script>

ể ứ ụ 55
● Câu l nh for...in đ c dùng đ l p m i thu c tính c a đ i t ng ho c m i
ph n t c a m t m ng.
● Cú pháp:
for (variable in object) {
statements;
}

ể ứ ụ 56
<script>
function myFunction(){
var x;
var txt="";
var person={Ho:"Nguyen Van",Ten:"Teo",age:27};
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>
</head>
<body>
<p>Nhấn nút để hiển thị tên</p>
<button onclick="myFunction()">Lấy thông tin</button>
<p id="demo">day la hien thi..</p>
</body>
ể ứ ụ 57
ể ứ ụ 58
● Câu l nh with đ c dùng đ th c thi t p h p các l nh mà các l nh này dùng các
ph ng th c c a cùng m t lo i đ i t ng.
● Thu c tính đ c gán cho đ i t ng đã đ c xác đ nh trong câu l nh with.
● Cú pháp:
with (object){
statements;
}

ể ứ ụ 59
<script>
with (document){
write(“This is an exemple of the things that can be done <br>”);
write(“With the with statment. <br>”);
write(“This can really save some typing”);
}
</script>

Kết quả:
This is an exemple of the things that can be done
With the with statment
This can really save some typing

ể ứ ụ 60
● new

objectName = new objectType(param1 [,param2] ...[,paramN])



o objectName
o objectType
o Param[1, 2, . . ]

ể ứ ụ 61
● Đ it ng String đ c dùng đ thao tác và làm vi c v i chu i văn b n.

● Cú pháp t ng quát:
stringName.propertyName
hay
stringName.methodName

ể ứ ụ 62

o Dùng l nh var và gán cho nó m t giá tr .
var string = “Test”;
o Dùng m t toán t (=) có gán v i m t tên bi n.
string = “test”;
o Dùng hàm kh i t o String(string)
string = new String(“Test”);

ể ứ ụ 63
● Đ i t ng Math có các thu c tính và ph ng th c bi u th các phép tính toán h c
nâng cao.
function doCalc(x) {
var a;
a = Math.PI * x * x;
alert ("The area of a circle with a radius of " + x + “ is " + a);
}

ể ứ ụ 64
● Mô t thông tin v : Ngày, Tháng, Năm, gi , phút, giây c a h th ng.
● Ví d : var now = new Date();

ể ứ ụ 65
Tên hàm Mô tả
getDate() Ngày: 1..31
getDay() Ngày trong tuần: 0 (chủ nhật), 1(thứ 2)
getHours() Giờ: 0..23
getMinutes() Phút: 0..59
getMonth() Tháng: 0 (tháng 1)…11(tháng 12)
getSeconds() Giây: 0..59
getTime() Giờ theo mili giây
getFullYear() Năm

ể ứ ụ 66
<script>
var now= new Date();
var ngay="";
ngay="hom nay la ngay"+ now.getDate();
ngay+=" thang "+now.getMonth();
ngay+=" nam " + now.getFullYear();
document.write(ngay) ;
</script>

ể ứ ụ 67
ể ứ ụ 68
● Các s ki n đ c h tr b i h u h t các đ i t ng
o onClick
o onFocus
o onChange
o onBlur
o onMouseOver
o onMouseOut
o onMouseDown
o onMouseUp
o onLoad
o onSubmit
o onResize
o ………
ể ứ ụ 69
● Cú pháp:
<TAG eventHandler = "JavaScript Code">
● Ví d :
<body>
<input type=“button” name=“Button1” value=“OpenSesame!”
onClick="window.open('mydoc.html');">
</body>
● L u ý: D u “…” và ‘…’ (nháy kép và nháy đ n)

ể ứ ụ 70
<head>
<script>
function GreetingMessage(){
window.alert(“Welcome to my world”);
}
</script>
</head>
<body onload=“GreetingMessage()”>
</body>

ể ứ ụ 71
● Gan
́ tên ham
̀ x lý cho 1 object event
object.eventhandler = function_name;
●Ví d :
<head>
<script>
function GreetingMessage(){
window.alert(“Welcome to my world”);
}
window.onload = GreetingMessage();
</script>
</head>

ể ứ ụ 72
<script>
function compute(){
var x = frm.expr.value;
result.innerHTML = x*x;
}
</script>
<form name="frm">
x = <input type="text" name="expr" size=15>
<br>
<input type="button" value=“Calculate” onclick="compute()"><br>
x * x = <span id="result"></span>
</form>

ể ứ ụ 73
ể ứ ụ 74
● X y ra khi m t thành ph n HTML nh n focus (onFocus) và m t focus (onBlur)
● Ví d :

<body bgcolor="lavender">
<form>
<input type=“text” name=“myTextbox”
onblur=“(document.bgColor='aqua')”
onfocus=“(document.bgColor='dimgray‘)” />
</form>
</body>

ể ứ ụ 75
onFocus onBlur

ể ứ ụ 76
Event Occurs when...
onabort a user aborts page loading
onblur a user leaves an object
onchange a user changes the value of an object
onclick a user clicks on an object
ondblclick a user double-clicks on an object
onfocus a user makes an object active
onkeydown a keyboard key is on its way down
onkeypress a keyboard key is pressed
onkeyup a keyboard key is released

ể ứ ụ 77
Event Occurs when...
onload a page is finished loading.
onmousedown a user presses a mouse-button
onmousemove a cursor moves on an object
onmouseover a cursor moves over an object
onmouseout a cursor moves off an object
onmouseup a user releases a mouse-button
onreset a user resets a form
onselect a user selects content on a page
onsubmit a user submits a form
onunload a user closes a page
ể ứ ụ 78
ể ứ ụ 79
● D O M

ể ứ ụ 80

ể ứ ụ 81
● Properties ● Methods
o document o alert
o event o confirm
o history o prompt
o location o blur
o name o close
o navigator o focus
o screen o open
o status

ể ứ ụ 82
● Ví d :
<html>
<body>
<script>
var curURL = window.location;
window.alert(curURL);
</script>
</body>
</html>

ể ứ ụ 83

ể ứ ụ 84
● Properties ● Methods
o document o documentElement
o close
o aLinkColor o cookie
o open
o bgColor o ……
o createTextNode(“text")
o body
o createElement(“HTMLtag")
o fgColor
o getElementById(“id”)
o linkColor
o getElementsByName(ten)
o title
o getElementsByTagName(Ten_The)
o URL
o vlinkColor o document.tenform.tencontrol.t
huoctinh
o forms[]
o images[]
o childNodes[]
ể ứ ụ 85

o document.tên_form

o Tên_form.Tên_ĐT

o Tên_thuộc_tính

ể ứ ụ 86
● getElementById(id1)
o Tr v node có giá tr thu c tính
● Ví d :
<p id="id1" >
some text Text Node
</p>
<script>
var node = document.getElementById(“id1”);
var nodeName = node.nodeName; // p
var nodeType = node.nodeType; // 1
var nodeValue = node.nodeValue; // null
var text = node.innerText ; // some text
</script>

ể ứ ụ 87
● createElement(nodeName)
o 1 node HTML nodeName
● Ví d :
<script>
var imgNode = document.createElement(“img”);
imgNode.src = “images/test.gif”;
</script>

<img src=“images/test.gif” />

ể ứ ụ 88
● createTextNode(content)
o nội dung node,
● Ví d :
<script>
var textNode=document.createTextNode("New text");
var pNode = document.createElement("p");
pNode.appendChild(textNode);
</script>

<p>New text</p>

ể ứ ụ 89
● appendChild(newNode)
o (newNode)
● Ví d :
<p id="id1" >
some text
</p>
<script>
var pNode = document.getElementById("id1");
var imgNode = document.createElement("img");
imgNode.src = "images/test.gif";
pNode.appendChild(imgNode);
</script>
<p id="id1" >
some text<img src=“images/test.gif” />
</p>
ể ứ ụ 90
● innerHTML
o nội dung HTML
● Ví d :
<p id=“para1" >
Some text
</p>
<script>
var theElement = document.getElementById("para1");
theElement.innerHTML = “Some <b> new </b> text”;
</script>

Kết quả : Some new text

ể ứ ụ 91
● innerText
o T ng t innerHTML, tuy nhiên b t kỳ n i dung nào đ a vào cũng đ c xem nh
là h n là các th .
● Ví d :
<script>
var theElement=document.getElementById("para1");
theElement.innerText = "Some <b> new </b> text";
</script>

// Kết quả hiển thị trên trình duyệt


“Some <b> new </b> text”

ể ứ ụ 92







ể ứ ụ 93
● s1=Intro.outerText
s2=Intro.innerText
thì s1 và s2 đều nhận giá trị Monitor SAMSUNG

● s1=Intro.outerHTML
s2=Intro.innerHTML
Thì s1=<Div Id=Intro>Monitor<B>SAMSUNG</B></Div>
Và s2=Monitor<B> SAMSUNG</B>

ể ứ ụ 94
ể ứ ụ 95
● số dòng, số cột

ể ứ ụ 96
<table> body
<tr>
<td> 12 </td> Table
<td> 13 </td>
Tr
</tr>
<tr> Td
<td> 21 </td> Td
<td> 22 </td>
Tr
</tr>
</table> Td
97
Td
ể ứ ụ
● document.createElement(…) :
● object.appendChild(…):

ể ứ ụ 98
<body>
<form name="frm">
Số dòng: <input type="text" name="txtdong"><br>
Số cột: <input type="text" name="txtcot"><br>
<input type="button" name="taoTable" value="Tao table"
onclick="createTable(document.getElementById('divTable'))">
</form>
<div id="divTable">
</div>
</body>

ể ứ ụ 99
function createTable(divTable){
var tagTable = document.createElement("table");
tagTable.border=1;
var nDong = frm.txtdong.value;
var nCot = frm.txtcot.value;
for (i=0;i<nDong;i++){
var tr = document.createElement("tr");
for (j=0;j<nCot;j++){
var td = document.createElement("td");
var textTd = document.createTextNode(i+""+j);
td.appendChild(textTd);
tr.appendChild(td);
}
tagTable.appendChild(tr);
}
divTable.appendChild(tagTable);
}
ể ứ ụ 100
<body>
<form name="frm">
Số dòng: <input type="text" name="txtdong"><br>
Số cột: <input type="text" name="txtcot"><br>
<input type="button" name="taoTable" value="Tao table" onclick="createTable()">
</form>
<table id="divTable">
</table>
</body>

ể ứ ụ 101
function createTable(){
var tagTable = document.getElementById("divTable");
tagTable.border =3;
var nDong = frm.txtdong.value;
var nCot = frm.txtcot.value;
for (i=0;i<nDong;i++){
var tr = document.createElement("tr");
for (j=0;j<nCot;j++){
var td = document.createElement("td");
var textTd = document.createTextNode(i+""+j);
td.appendChild(textTd);
tr.appendChild(td);
}
tagTable.appendChild(tr);
}
ể ứ ụ 102

ể ứ ụ 103
● setTimeout(f, n)


o setTimeout(f, n)
o clearTimeout(timeID)
o intervalID = setInterval(f, n):

o clearInterval(intervalID):

o str.length:
o str.substr(i, n):

ể ứ ụ 104

o

o B1:
o B2: str

o B3:

ể ứ ụ 105
<script>
var str= 'Dai Hoc Cong Nghe Thong Tin’;
for (i=str.length; i<100; i++){
str = str + ' ‘;
}
function ChuChay(){
var tagDiv = document.getElementById("chaychu");
tagDiv.innerText = str;
str = str.substr(1,str.length-1) + str.substr(0,1);
setTimeout(ChuChay,100);
}
</script>
<body onload="ChuChay()">
<div id="chaychu">
</div>
</body>

ể ứ ụ 106

ể ứ ụ 107
ể ứ ụ 108

ể ứ ụ 109
● Xử lý đồng bộ (Synchronous)

ể ứ ụ 110

ể ứ ụ 111
● Multi-thread

ể ứ ụ 112
● Xử lý bất đồng bộ: Asynchronous

ể ứ ụ 113

○ Callback
○ Promise
○ Async/await

ể ứ ụ 114

You might also like