1. Trang chủ
  2. » Tất cả

websystemsandtechnologies 04 javascript

67 1 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 67
Dung lượng 2,67 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 04 Java Script Web Systems and Technologies Content What is JavaScript The Foundation of JavaScript Syntax The Core language Objects in JavaScript Document Object Model (DOM) and The Brows.

Trang 1

Chapter 04 Java Script Web Systems and Technologies

Trang 2

 What is JavaScript

 The Foundation of JavaScript Syntax

 The Core language Objects in JavaScript

 Document Object Model (DOM) and The Browser Objects inJavaScript

Trang 3

The Foundation of JavaScript Syntax

Trang 4

Microsystems and Netscape.

 JavaScript developed from Netscapes’s Livescript

Navigator, Google Chrome, FireFox or Internet Explorer

Trang 5

JavaScript Advantages

 JavaScript allows interactivity such as:

 Implementing form validation

 React to user actions, e.g handle keys

 Changing an image on moving mouse over it

 Sections of a page appearing and disappearing

 Content loading and changing dynamically

 Performing complex calculations

 Custom HTML controls, e.g scrollable table

 Implementing AJAX functionality

Trang 6

What Can JavaScript Do?

 Can handle events

 Can read and write HTML elements and modify the DOM tree

 Can validate form data

 Can access / modify browser cookies

 Can detect the user’s browser and OS

 Can be used as object-oriented language

 Can handle exceptions

 Can perform asynchronous server calls (AJAX)

Trang 7

Embedding JavaScript in Web Page

 The JavaScript can be inserted into an HTML document in thefollowing ways :

 Using SCRIPT tag:

<script language="JavaScript">

JavaScript statements;

<! // >

</script>

 Using an external File

<script language="JavaScript“ src="filename.js">

</script>

 Using JavaScript Expressions within HTML Tag Attribute Values

 Using JavaScript in event handlers

Trang 8

JS Variables

 A variable is a container that refers to a memory location

 It is used to hold values that may change while the script isexecuting

 Variables follow some naming conventions

 A variable is declared using the keyword ‘var’.

Trang 9

JS Variables (1)

 String type – string of characters

 Arrays

 Associative arrays (hash tables)

var myName = "You can use both single or double quotes for

strings";

var my_array = [1, 5.3, "aaa"];

var my_hash = {a:2, b:3, c:"text"};

Trang 11

JS Data Type - Example

Trang 12

JS Literal - Types

 Integer – These can be expressed in decimal, hexadecimal and

binary number system

 Floating- point - These number can have a decimal point or an

“e” or “”E” followed by an integer

 String - A string literal is zero or more characters enclosed in single

or double quotation marks

 Boolean - This can take only two values: True or False

 null - The null type has only one value: null Null implies no data

Trang 13

 Operators take one or more variables or values (operands) and

return a new value

 JavaScript uses both binary and unary operators

 Operators are classified depending on the relation they perform

Trang 14

Evaluation Operator

 These operators generally includes:

 Conditional operator

(condition) ? trueVal : falseVal

Assigns a specified value to a variable if a condition is true,otherwise assigns an alternate value if condition is false

eg status = (age >= 18) ? "adult" : "minor"

Trang 15

case 'a':

// do something else break;

case 3.14:

// another code break;

default:

// something completely different }

switch-statements.html

Trang 16

}

Trang 17

 JavaScript has several pre-defined functions that we can use

within the script

 Some of pre-defined JavaScript functions includes:

Trang 18

Function (1)

 Code structure – splitting code into parts

 Data comes in, processed, result returned

Declaring variables is optional Type is never

declared

Value returned

here

Trang 19

Function Arguments and Return Value

 Functions are not required to return a value

 When calling function it is not obligatory to specify all of itsarguments

 The function has access to all the arguments passed viaarguments array

Trang 20

Standard Popup Boxes

 Alert box with text and [OK] button

 Just a message shown in a dialog box:

 Confirmation box

 Contains text, [OK] button and [Cancel] button:

 Prompt box

 Contains text, input field with default value:

alert("Some text here");

confirm("Are you sure?");

prompt ("enter amount", 10);

Trang 21

JavaScript Prompt – Example

price = prompt("Enter the price", "10.00");

alert('Price + VAT = ' + price * 1.2);

Trang 22

The Core language Objects in JavaScript

Trang 23

In JavaScript, almost "everything" is an object

 Booleans can be objects (or primitive data treated as objects)

 Numbers can be objects (or primitive data treated as objects)

 Strings can be objects (or primitive data treated as objects)

 Dates are always objects

 Maths are always objects

 Regular expressions are always objects

 Arrays are always objects

 Functions are always objects

 Objects are objects

 In JavaScript, all values, except primitive values, are objects

Trang 24

Properties and Methods

 To access the properties of the object, we must specify the objectname and the property:

objectName.propertyName

 To access the methods of an object, we must specify the objectname and the required method:

objectName.method()

Trang 25

 We can also create our own objects for use in the programs.

 Object Hierarchy Browser Objects

Script Objects

Trang 28

New Operator

 The new operator is used to create a new instance of an objecttype

 The object type may be user-define or built-in

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

where,

objectName is the name of the new object instance.

objectType is a function that defined the type of the object For

example, Array

param[1, 2, ] are the property values of the object

Trang 29

Create new Object

 With JavaScript, you can define and create your own objects

 There are different ways to create new objects:

 Define and create a single object, using an object literal

 Define and create a single object, with the keyword new

 Define an object constructor, and then create objects of theconstructed type

 Step 1: Create new object by create a function

 Step 2: Create new instant by using new operator

Trang 30

Creating String object

 There are 3 different methods of creating strings

 Using the var statement and optionally assigning it to a value

 Using an assignment operator (=) with a variable name

 Using the string () constructor

<script type = "text/javascript">

var str = “Steve Paris!"

document.write("<p>" + str + "</p>") document.write(str.length)

var pos=str.indexOf(“Paris")

if (pos>=0) { document.write(“Paris is found at position: ")

document.write(pos + "<br />") } else

Trang 31

Create new Object - Example

Example: Create an object named Customer:

 Properties: CustomeriD, CustomerName,CustomerAddress

function Customer( iD,name,address)

{ this.CustomeriD = iD; //property

this.CustomerName = name; //property this.CustomerAddress = address; //property this.Displayinfor = information; //method }

Trang 32

Create new Object – Example (2)

Step 2.

var cust = new Customer();

cust.CustomeriD= “A01”

cust.CustomerName= “Steve Paris”

cust.CustomerAddress= “12 Orange Street”

 In order to display customer’s information, we call Displayinfor()method:

cust.Displayinfor()

Trang 33

Arrays Operations and Properties

 Declaring new empty array:

 Declaring an array holding few elements:

 Appending an element / getting the last element:

 Reading the number of elements (array length):

 Finding element's index in the array:

var arr = new Array();

Trang 35

Math Object Example

for (i=1; i<=20; i++) {

Trang 36

Date Object

 The Date object provides date / calendar functions

var now = new Date();

var result = "It is now " + now;

document.getElementById("timeField").innerText = result;

<p id="timeField"></p>

Trang 37

Timers: setTimeout()

 Make something happen (once) after a fixed delay

var timer = setTimeout('bang()', 5000);

Trang 38

Timers: setInterval()

 Make something happen repeatedly at fixed intervals

var timer = setInterval('clock()', 1000);

Trang 39

Date Object Example

<body BGCOLOR="#FFFFFF” onLoad="startclock()">

</body></html>

<html><head>

<title>Digital Clock - Status Bar</title>

<script Language="JavaScript">

var timeriD = null;

var timerRunning = false;

var now = new Date();

var hours = now.getHours();

var minutes = now.getMinutes();

var seconds = now.getSeconds() var timeValue = "" + ((hours >12) ? hours -12:hours) timeValue += ((minutes < 10) ? ":0": ":") + minutes timeValue += ((seconds < 10) ? ":0": ":") + seconds timeValue += (hours >= 12) ? " P.M.": " A.M."

window.status = timeValue;

timeriD = setTimeout("showtime()",1000);

Trang 40

Document Object Model (DOM)

and The Browser Objects in JavaScript

Trang 41

Event Object - Concept

 Events are a result of an action done by the user

 An event may be user-generated or generated by the system

 Each event has an associated event object The event objectprovides information on:

 the type of event

 the location of the cursor at the time of the event

 The event object is used as a part of an event handler

Trang 42

Event – Life Cycle

 Events are a result of an action done by the user

 An event may be user-generated or generated by the system

 Each event has an associated event object The event objectprovides information on:

 the type of event

 the location of the cursor at the time of the event

 The event object is used as a part of an event handler

Trang 44

alert("Please come back again.") }

</SCRIPT>

</HEAD>

<BODY>

Trang 45

onClick – Example (2)

Enter an expression:

<INPUT TYPE="text" NAME="expr" SIZE=15 ><BR><BR>

<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)">

<BR><BR><BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 >

<BR>

</FORM>

</BODY>

</HTML>

Trang 46

onChange - Example

 The onChange event occurs whenever a form element changes.This can happen whenever the contents of a text controlchanges, or when a selection in a selection list changes

Trang 47

<BODY bgColor = white>

<FORM> Please enter a number:

<INPUT type = text size = 5 onChange="checkNum(this.value)">

</FORM>

</BODY>

</HTML>

Trang 49

 onMouseDown

 The event is activated when a MouseDown event occurs That

is, when the user depresses a mouse button

 onMouseUp

 The event is activated when a MouseUp event occurs That is,when the user releases a mouse button

Trang 50

Document Object Model (DOM)

 Every HTML element is accessible via the JavaScript DOM API

 Most DOM objects can be manipulated by the programmer

 The event model lets a document to react when the user doessomething on the page

 Advantages

 Create interactive pages

 Updates the objects of a page without reloading it

Trang 52

Accessing Elements

 Access elements via their ID attribute

 Via the name attribute

 Via tag name

 Returns array of descendant <img> elements of the element

"el"

var elem = document.getElementById("some_id")

var arr = document.getElementsByName("some_name")

var imgTags = el.getElementsByTagName("img")

Trang 53

DOM Manipulation

 Once we access an element, we can read and write its attributes

function change(state) {

var lampImg = document.getElementById("lamp");

lampImg.src = "lamp_" + state + ".png";

var statusDiv = document.getElementById("statusDiv");

statusDiv.innerHTML = "The lamp is " + state";

}

<img src="test_on.gif" onmouseover="change('off')"

onmouseout="change('on')" />

Trang 54

Common Element Properties

 Most of the properties are derived from the HTML attributes of thetag

 E.g id, name, href, alt, title, src, etc…

 style property – allows modifying the CSS styles of the element

 Corresponds to the inline style of the element

 Not the properties derived from embedded or external CSSrules

 Example:

 style.width,

 style.marginTop,

 style.backgroundImage

Trang 55

Common Element Properties (2)

 className – the class attribute of the tag

 innerHTML – holds all the entire HTML code inside the element

 Read-only properties with information for the current element andits state

 tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop,nodeType, etc…

Trang 56

Accessing Elements through the DOM

Trang 57

Accessing Elements through the

DOM Tree – Example

 Warning: may not return what you expected due to Browserdifferences

Trang 58

The Built-In Browser Objects

Trang 59

The Built-In Browser Objects (2)

 The browser provides some read-only data via:

 window

 The top node of the DOM tree

 Represents the browser's window

Trang 60

Opening New Window – Example

var newWindow = window.open("", "sampleWindow",

"width=300, height=100, menubar=yes,

Trang 61

The Navigator Object

alert(window.navigator.userAgent);

The navigator in the browser window

The userAgent (browser ID) The browser

window

Trang 62

The Screen Object

 The screen object contains information about the display

window.moveTo(0, 0);

x = screen.availWidth;

y = screen.availHeight;

window.resizeTo(x, y);

Trang 63

Document and Location

Trang 66

Form Validation – Example

<form name="mainForm" onsubmit="return checkForm()">

<input type="text" name="firstName" />

Ngày đăng: 15/11/2022, 22:38

w