【高级程序设计】Week2-4&Week3-1 JavaScript

一、Javascript

1. What is JS

定义 A scripting language used for client-side web development.
作用

an implementation of the ECMAScript standard

defines the syntax/characteristics of the language and a basic set of commonly used objects such as Number, Date

supported in browsers supports additional objects(Window, Frame, Form, DOM object)

One Java

Script?

Different brands and/or different versions of browsers may support different implementations of JavaScript.

– They are not fully compatible.

– JScript is the Microsoft version of JavaScript.

2. What can we do with JS

Create an interactive user interface in a webpage (eg. menu, pop-up alerts, windows)

Manipulate web content dynamically

Change the content and style of an element

Replace images on a page without page reload

Hide/Show contents

Generate HTML contents on the fly

Form validation

3. The lanuage and features

Validation Validating forms before sending to server.
Dynamic writing Client-side language to manipulate all areas of the browser’s display, whereas servlets and PHPs run on server side.
Dynamic typing Interpreted language (interpreter in browser): dynamic typing.
Event-handling Event‐Driven Programming Model: event handlers.
Scope and Functions Heavyweight regular expression capability
Arrays and Objects Functional object‐oriented language with prototypical inheritance (class free), which includes concepts of objects, arrays, prototypes

4. Interpreting JS

Commands are interpreted where they are found

– start with tag, then functions in or in separate .js file

static JavaScript is run before is loaded

– output placed in HTML page

        • [document.write() ... dynamic scripting]

        •

enter your email

Cakes Cost £1 each

enter no. cakes
Total Price

三、 Dynamic Typing

1. Type is defined by literal value you assign to it

【高级程序设计】Week2-4&Week3-1 JavaScript_第1张图片

2. Implicit conversion between types【高级程序设计】Week2-4&Week3-1 JavaScript_第2张图片

"string1"+"string2" = "string1string2"   //string的拼接

10 + "string2"="10string2"                   //将int类型的10,转换成string

true + "string2" = "truestring2"             //将Boolean类型转换为string

.123 + "string2" = ".123string2"           //将float类型转换为string


10 + .123 = 10.123                             //将int转换为float,进行数值加减

true + .123 = 1.123                             //将Boolean类型转换为float,进行数值加减

false + 10 = 10                                   //将Boolean类型转换为int,进行数值加减

false + true = 1                                   //进行逻辑运算


a = 1; b = “20”;

c = a + b;//"120"

c = b + a;//"201"

// prefers numeric conversion with minus (and prefers string conversion with +).

c = a + (b-0);//21

// The empty string, forcing conversion into a string

c = a + “”;//"1"


x = 7; y = 4;

sum = x + y;//11

document.writeln(“x + y = ” + sum + “”);        //11

document.writeln(“x + y = ” + x+y + “”);         //74

document.writeln(“x + y = ” + (x+y) + “”);       //括号中的表达式被当作数值相加运算,11

3. Quotes within strings&writeln

Quotes within strings document.write(“He said, \"That’s mine\" ”); 
document.write(‘She said, "No it\'s not" ');
• Beware of splitting over lines

writeln()-new lines

(avoid-not expected)

writeln: adds a return character after the text string

:get a line break on the page
using headers:document.write(“

Top level header”

);

document.write(‘
’): get a
 line break

4. Comparison Operators

== and != do perform type conversion before comparison “5”==5 is true
=== and !== do not perform type conversion “5”===5 is false

const cakePrice = 1;        const bunPrice = 0.5;
var noCakes = document.getElementById("cake").value;
var noBuns = document.getElementById("bun").value; 
document.getElementById("count").value = noCakes + noBuns; document.getElementById("total").value = "£" + cakePrice*noCakes + bunPrice*noBuns;

5. Explicit Conversion Functions

eval() takes a string parameter and evaluates it

x = eval(“123.35*67”);        //123.35*67

eval(“x=1; y=2; x+y”);        //1+2

parseInt()
 
returns the first integer in a string; if no integer returns NaN.

parseInt(“xyz”)         //returns NaN

parseInt(“123xyz”)   //returns 123 as an integer

parseFloat()

parseFloat(“123.45xyz”) returns 123.45

isNaN()

returns true if input is not a number

isNaN(“4”)        //returns false

isNaN(4)          //returns false

isNaN(parseInt(“4”))         //returns false

isNaN(parseInt(“four”))     //returns true

Concatenation

issue with using +: implicit string conversion

parseInt(“99”)        //99

parseInt(99)          //99

parseInt(“99 red balloons”)        //99

字符串以 "0" 开头且后面紧跟着数字字符,则被假定为八进制。字符串"099"以 "0" 开头,因此parseInt()函数会将基数视为八进制。然而,数字 9 在八进制中是无效的,因此解析过程会停止,并返回十进制的结果,即99。

– This may affect code where trying to, e.g. parse dates and times.


     
        
    
    
         

Cakes Cost £1 each; Buns 50p each

enter no. cakes
enter no. buns
number of units
Total Price

四、Event-handling

1. Event-Diven Programming

Event-Diven Programming Web browser generates an event whenever anything ‘interesting’ occurs.
registers an event handler
event handlers  enter phone no.
focus event … onfocus event handler
blur event … onblur event handler
change event … onchange event handler
user types a char … onkeyup event handler
event handlers 
as HTML element attributes

onclick=validate()>

– Calls validate() function defined in .
– Case insensitive (HTML): onClick=validate() .
– Can then force form to submit , e.g. document.forms[0].submit();

Main version used in course examples:

onSubmit=“return validate()”> // textboxes

//  If onSubmit=validate() [ omit ‘ return ’], this will still send the user input to the server side even if it fails the validation.

2. Feedback (Forms and JavaScript, Event Handling)

write the HTML:

user guidance, 2 textboxes, button (not ‘submit’)

– name the elements
       Name
      Email
       
getting the button

Where and How to write JavaScript functions
function validate() {
   if (window.document.forms[0].usrname.value =="")
           window.alert(“Please enter name:”);
}
Global window object

3. Dynamic Writing

Document Object Model & Empty String
• API for HTML and XML documents:
-Provides structural representation of a document , so its content and visual presentation can be modified.
-Connects web pages to scripts or programming languages.
• Navigating to elements and accessing user input: textboxes , textareas ...
        Name text” name=“usrname”/>
        Email text” name=“usremail”/>
        button” onClick=“validate()” value=“Send”/>
focus() and  modifying the value
document.getElementById(“usrname").focus();
d = document.getElementById(“usrname");
if (d.value == “”)         d.value = “Please input!”;
Modifying the HTML page to notify
Name

function validate() {
  var d = window.document.forms[0];
  if (d.usrname.value == “”)
     window.document.getElementById(“name”).innerHTML = “Enter”;
}


    
    
    
    
        
        

Please enter details

Name  

Email  

五、 Arrays and Objects

1. Strings & Intervals

Useful string functions for validation
if (ph.charAt(i)>=‘A’ && ph.charAt(i) <= ‘Z’)  // character at index i of this variable
if (ph.length < 9) // the length of this variable
if (ph.substring(0, 1) == ‘,’) // substring,  could first iterate through user input to extract all non-digits, then use substring to extract area code.
if (ph.indexOf('@') == 0) //  index of character (charAt ) ,  emails never start with @
setInterval()
        
                DHTML Event Model - ONLOAD
        
        
        
                

Seconds you have spent viewing this page so far:

                 “soFar” STYLE = “font-weight: bold”> 0

//文本连接
         
Handling Delays setTimeout() delay before execution
setInterval() interval between execution
clearInterval()
clearTimeout()
setTimeout(myFunc(), 1) delay 1 ms
setTimeout(myFunc(),1000) delay 1 second
myVar = setInterval(myFunc(), 1000)
myVar = setInterval(myFunc(), 1000)

2. JavaScript and Functions

JavaScript functions are objects can be stored in objects, arrays and variables
can be passed as arguments or provided as return values
can have methods (= function stored as property of an object)
can be invoked
call a function (Local call) directly: var x = square(4);
(Callback) in response to something happening: called by the browser, not by developer’s code: events; page update function in Ajax

3. Arrays and Objects

Array Literal
list = [“K”, “J”, “S”];
var list = [“K”, 4, “S”]; // mixed array
var emptyList = [];
var myArray = new Array(length);
// array constructor
employee = new Array(3);
employee[0] = “K”; employee[1] = “J”;
employee[2] = “S”;
document.write(employee[0]);
new Object() / /A new blank object with no properties or methods.
employee = new Object();
employee[0] = “K”;
var a = new Array();
new Array(value0, value1, ...);
employee = new Array(“K”, “J”, “S”);
document.write(employee[0]);
Sparse Arrays
new Array();  // Length is 0 initially; automatically extends when new elements are initialised.
employee = new Array();
employee[5] = “J”; // length:  6
employee[100] = “R”; //l ength :  101
length is found as employee.length
No array bounds errors.
Associative array or object
A = new Object();
A["red"] = 127;
A["green"] = 255;
A["blue"] = 64;
A = new Object();
A.red = 127;
A.green = 255;
A.blue = 64;

   

4. Scope and local functions

html>Functions 



JavaScript and Scope Clike languages have block scope:declare at first point of use
JavaScript has function scope:variables defined within a function are visible everywhere in the function
declare at the start/top of the function body.
Inner functions can access actual parameters and variables (not copies) of their outer functions.

六、Cookies

作用
allow you to store information between browser sessions, and
you can set their expiry date
默认 browser session
包含 A name-value pair containing the actual data.
An expiry date after which it is no longer valid.
The domain and path of the server it should be sent to.
Storing a cookie in a JavaScript program
document.cookie = “version=” + 4;
document.cookie = “version=” + encodeURIComponent(document.lastModified);
• Stores the name-value pair for the browser session.
• A cookie name cannot include semicolons,commas, or whitespace
– Hence the use of encodeURIComponent(value) .
– Must remember to decodeURIComponent() when reading the saved cookie.
document.cookie = "version=" + encodeURIComponent(document.lastModified) +
" ; max-age=" + (60*60*24*365);
only the name-value pair is stored in the name-value list associated with  document.cookie .
• Attributes are stored by the system.
//A Cookie to remember the number of visits

    
        How many times have you been here before?
        
    
    
    

七、PROBLEMS WITH USER INPUT

1. A Cautionary Tale: SQL Statements

Enter phone number to retrieve address
– ' ||'a'='a
– No validation
Name=value pair, PhoneNumber=‘||’a’=‘a, passed to server Server side: access/update database information using SQL statements.
SELECT * FROM table_name WHERE phone=‘parameter

SELECT * FROM table_name WHERE phone=‘02078825555

SELECT * FROM table_name WHERE phone=‘asdsdaEN3

SELECT * FROM table_name WHERE phone=‘ ’||’a’=‘a
• i.e. SELECT * FROM table_name WHERE phone=‘’ OR ‘a’=‘a’

2. Further Examples of Event Handling

Buttons submitting to, e.g. CGI: value=“Send”>
onClick:
Text Boxes onBlur=“typeNothing()”>
When the document is first loaded
or
(inside
Name:
Email:
Click here if you like this site
Any comments?

//Element objects & ONLOAD


    Object Model
    


    

Welcome to our Web page!

//Changes when alert box is clicked. //pText.innerText or document.getElementById(“pText”).innerHTML //More inner text – from Microsoft (Altering Text)

Here's the text that will change.

你可能感兴趣的:(高级程序设计,javascript,开发语言)