
307070ba74d05565b8daac87425396f0.ppt
- Количество слайдов: 35
Java. Script
Overview Introduction: Java. Script basics n n Expressions and types Arrays Objects and Associative Arrays Functions Java. Script in a web browser n n Invoking Java. Script for accessing and modifying HTML content Dynamic HTML (DHTML) Sample programs
Language Fundamentals Powerful Object Oriented Language But very different from Java, C#, or C++ Dynamic and interpreted n Can easily define new functions at runtime Built in support for regular expressions Designed for web browser interactions Actually a powerful programming language Can also be run stand-alone on server n E. g. using Rhino
Types Boolean Number (just one type for number; c. f. Java which has int, float, double, char, …) Array Associative array / Object Function When programming in a given context e. g. a web browser n n Many additional types (e. g. HTML Elements and Attributes) These are all types of Object
Expressions (from Flanagan, p. 59) 1. 7 // a numeric literal “Java. Script is Fun!” // string literal true // boolean literal null // the literal null value /java/ // a regular expression literal { x: 2, y: 2 } // an object literal or associative array [2, 3, 5, 6] // an array literal function(x) {return x*x} // function literal i // the variable i sum // the variable sum
Higher Order Functions can take other functions as arguments n These are known as ‘higher -order functions’ This allows for great flexibility when programming Question: n n How can similar things be done with Java? There are two ways…
Main Features Great for interactive web pages n Validation, calculation, messages Supported by most full-feature browsers n IE, Netscape, Mozilla, Opera, …(though varying support) Place n n In-line Or reference in separate file (good for common functions) C-like syntax Access to current HTML page via DOM n (Document Object Model) Weakly typed (c. f. Java’s Strong Typing) n Also called ‘Duck Typing’
Java. Script Programming Event Handling Statements (like C / Java) Operators Variables global (default) n Or local (e. g. var x = 1) Types can change n Eg. x = 1; x = ‘Hello’ Function definition (decompose problem / reuse) Message Alerts Page element access with Document Object Model n Views HTML page as a tree of elements
Document Object Models (DOMs) Source of confusion: there are two document object models: Legacy DOM W 3 C DOM (Levels 1 and 2; details won’t concern us too much here) They do similar things but in different ways n n Legacy DOM is concise but awkward W 3 C DOM is less concise, but has consistent naming conventions
Legacy DOM Idiosyncratic naming of page elements You’ll need a reference guide constantly at hand to find the correct names to use n The names of properties do NOT correspond to their HTML names Example: n n n document. anchors[] an object collection listing all the bookmarks in a document i. e. <a> tags with name instead of href e. g. <a name=“Conclusions>Conclusions</a> other examples include links[], forms[], images[]
W 3 C Document Object Model Has consistent naming scheme Example methods: n document. get. Element. By. Id(“unique. Id”); Returns a single element n document. get. Elements. By. Tag. Name(“a”); Returns an array of elements – in this case all the <a> tags in the document
Hello World Example This provides an annoying popup – try it! <html> <body> <a href="http: //www. google. co. uk" on. Mouse. Over="( alert( 'Follow link to search on Google') )"> Search on Google </a> </body> </html>
Invoking Java. Script From a URL n <a href=“javascript: my. Func()” > Click here to invoke my. Func() </a> From an input event handler (see Hello World example) From a page load event <body onload=“my. Func()”> From a timer n n e. g. set. Interval(image. Refresh, 100); Calls the (user defined) image. Refresh() function every 100 milliseconds
Handling Events An event can invoke any valid Javascript n n One or more statements Usually a function call Activated as we saw previously: n <tag attribute 1 attribute 2 on. Event. Name="javascript code; ">
Common Events An event is given a Name to identify it The handler for an event gets called when the event occurs The handler takes the form on. Event. Name E. g. the code for on. Mouse. Over is called when the mouse hovers over a link Select n User enters a form element (on. Select) Change n Use changes a form element then leaves it (on. Change) Submit n clicks the submit button on a form (on. Submit)
Defining Functions function func. Name(arg 1, arg 2, etc) { statements; } Note: n n n No type information in function signature Can declare a function with no args, then pass it some! and access with arguments array within function Example: factorial n n n Recursive calculation Conditional statement Calling from Change event Use of document. get. Element. By. Id Use of this. value – gets value of current element
Factorial Form <html> <head> <script language="Java. Script"> function fac(n) { // do it recursively. . . if (n < 2) { return 1; } else { return n * fac(n-1); } } </script> </head>
Factorial Form Contd. <body> <form> <p> <input id="fac. Arg" type="text" onchange=" result = fac(this. value); document. get. Element. By. Id('fac. Result '). value = result; " /> </p> <input id="fac. Result" type="text" /> </p> </form> </body> </html>
Form in action
Invoking JS from Hyperlinks Java. Script code can be the destination for a hyperlink Use: n <a href=“javascript: my. Func(‘arg’)”>Click here to invoke my. Func(arg)</a> Example below uses this to dynamically change the appearance of a list
List Change Function
List Change Usage
Note usage of In Java. Script function list. Style() n n document. get. Element. By. Id(id); set. Attribute(“class”, value); In HTML n n Function call on href Alternative string quotes ‘’ to pass argument: list. Style(‘no. Bullet’); n id=“my. List” to identify the list
Sorting Example Sort Numbers or Strings Default: everything converted to a string n Provide a comparator to override this
Our Java. Script test() function
Running Sort This was after clicking middle (buggy) sort
Eval Function Any String can be interpreted as ‘Live’ Java. Script code using the ‘eval’ function Can use this to write a code runner
HTML for Eval
Java. Script Evaluation
Eval Screenshot (Firefox)
Multi-Window Communication The following simple example illustrates multiwindow communication n n A child window is created, filled with content, and talks back to parent Can be used for Calendar controls etc. Note use of window. open() to create a new window (a child window) n n Then writing to the document object of that window And writing to the parent window (opener)
JS for Window Creation
Invisible HTML for Popup Content
Exercise: Explain what happened:
Summary Concise – due to weak / dynamic typing DOM gives great power to access / modify HTML page n See auto Table of Contents Example in Lab Can look up elements by ID Event-handling n Makes forms interactive Good for validation / dialog Use Javascript console (Mozilla) for debugging See also AJAX (Google it)
307070ba74d05565b8daac87425396f0.ppt