صفحه 1:
HTML Documents and
JavaScript
جاوا اسكرييتو HTML 1
پخش هایی از جاوا اسکریپت نوشته شده توسط
Tom Horton & Alfred C. Weaver
تکمیل » ویرایش و ترجمه : گروه ۲
(طلیفی نوری پزاوند. طیبیلسنزادم)
صفحه 2:
= Many “markup” languages in the
past
= SGML: Standard Generalized Markup
Language
= HTML (Hypertext Markup Language)
based on SGML
= XML (eXtensible Markup Language)
“replaces” SGML
= XHTML is replacing HTML
صفحه 3:
تگ ها و اجزای آنها
= Example of an element:
<name attrl=“attrval”>content</name>
= Begin and end tags set off a section of a
document
= Has a semantic property by tag-name
= Modified by attributes
= “content” can contain other elements
= Empty-elements: no end tag
= <br/> <img... />
= Note space before />
صفحه 4:
مقدمات ساختاری html 4
<--- title, meta-
tags, etc. (not
displayed)
<--- main content
(displayed)
= Comments:
<!-- +>
= Example:
<html>
<head>
</head>
<body>
</body>
</html>
صفحه 5:
یک مثال کامل
<p>
<ol type="I" start=7>
<li><font
color=#00FF00>Green</fon
t></li>
<li>Yellow</li>
<ul type=square>
<li>john</li>
<li>Mike</li>
</ul>
</ol>
</p>
</body>
</htm|>
<htmi>
<head>
<title>An Example</title>
</head>
<body>
<h3><hr>An Example</h3>
<p align="left"
‘Comic Sans MS"
<< ><
Hello World! </b></font>
</p>
<p align="right">
"><u>lam
21.</u></font>
</p>
<!-- see next column -->
صفحه 6:
خروجی مثال
666 ‘An Example
S & Bete حا Google Ql
Getting Started Latest Headlines) Appley Amazon eBay >|
‘An Example
Hello World!
lam 21.
VIL. Green
VIL Yellow
= Joba
= Mike
Done
صفحه 7:
= Text display:
= <em>, <strong>, <em>
= Structure:
=" <hl>, <h2>, <h3>
"<p>
= <ul>, <ol>, <blockquote>
= Attributes:
= Align, text, bgcolor, etc.
صفحه 8:
فقندمات SG ها 4
= Links:
<a href=“...">...</a>
= Images:
= <img src="..."> an empty tag
= Tables
= Use an editor!
= Forms: later
صفحه 9:
زبان برنامه نویسی شی گرا
An model for describing HTML =
documents (and XML documents)
A standard (ok, standards) =
Independent of browser, language "
(ok, mostly) =
APIs in JavaScript, for Java, etc. =
صفحه 10:
DO M HISTORY LOCATION
= You get
anything you
want from...
= More info:
http://en.wikipedia.org/wiki/Document
_Object_Model
صفحه 11:
استاندارهای )۷/3
= XML, XHTML
=" CSS, XSL
= XSLT
= DOM
=" ECMAScript
= etc
صفحه 12:
جاوا سکریپت
= An example of a “scripting”
langauge that is embedded in
HTML documents
" The browser’s display engine must
distinguish from HTML and Script
statements
= Others like this:
= PHP (later in the course)
صفحه 13:
تاریخچه 4
= JavaScript created by Netscape
= JScript created by Microsoft
= IE and Netscape renderings are slightly
different
= Standardized by European Computer
Manufacturers Association (ECMA)
= http://www.ecma-international.
org/publications /standards/Ecma-
262.htm
13
صفحه 14:
<!doctype ...>
<html>
<Head>
<Title> Name of web page </title>
<script type="text/javascript">
..Script goes here
</script>
</head
<body>
...page body here: text, forms, tables
..more JavaScript if needed
..onload, onclick, etc. commands here
</body>
</htmI>
14
صفحه 15:
ساختار زبانی 4
= Case sensitive
= Object oriented
= Produces an HTML document
= Dynamically typed
= Standard operator precedence
= Overloaded operators
= Reserved words
صفحه 16:
ساختار زبانی
= Division with / is not integer division
= Modulus (%) is not an integer operator
"5/2 yields 2.5
= 5.1/2.1 yields 2.4285714285714284
"5 % 2 yields 1
= 5.1% 2.1 yields 0.8999999999999995
صفحه 17:
ساختار زبانی
"and ' can be used in pairs
Scope rules for variables
Strings are very common data types
Rich set of methods available
Arrays have dynamic length
Array elements have dynamic type
Arrays are passed by reference
Array elements are passed by value
صفحه 18:
دستورات مهم در جاوا Saul
while loops
do-while loops
if-else
variable values in tags
math library
switch
break
labeled break
continue
Booleans
18
code placement
document.writeln
document tags
window.alert
user input/output
parselnt and parseFloat
arithmetic
arithmetic comparisons
for loops
صفحه 19:
دستورات مهم
arrays
searching
strings
substrings
string conversions
markup methods
19
در جاوا اسکر
functions
random numbers
rolling dice
form input
form output
submit buttons
games
صفحه 20:
فراخوانی جاوا اسکر 4
= Create functions (non-OO style)
= Define in header
= Or load a ز. file in header:
<script type="text/javascript"
language="javascript" src="mylib.js">
= Functions called in <BODY>
= Often in response to events, e.g.
<input type="button".. onclick="myFunc(...) ;">
= Global variables
20
صفحه 21:
document.writeln
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!- Welcome to JavaScript -->
<HEAD>
<TITLE> Welcome to JavaScript </TITLE>
<SCRIPT TYPE="text/javascript">
document.writeln( "<FONT
COLOR='magenta'><H1>Welcome to ",
‘JavaScript Programming!</H1></FONT>" );
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
21
صفحه 22:
document.write
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
1TML>
1EAD>
ITLE> Using document.write </TITLE>
>CRIPT TYPE="text/javascript">
document.write (_ "<H1>Welcome to ");
document.writeln( "JavaScript Programming! </H1>" );
SCRIPT>
HEAD>
30DY>
BODY>
HTML>
22
صفحه 23:
window.alert
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
{TML>
{EAD>
ITLE> Using window.alert </TITLE>
>CRIPT TYPE="text/javascript">
window.alert( "Welcome to\nJavaScript\nProgramming!" );
SCRIPT>
HEAD>
30DY>
>>Click Refresh (or Reload) to run this script again.</P>
BODY>
HTML>
23
صفحه 24:
var firstNumber, // first string entered by user
secondNumber, // second string entered by user
number1, // first number to add
number2, // second number to add
sum; // sum of number1 and number2
// read in first number from user as a string
firstNumber = window.prompt("Enter first integer", "O'
// read in second number from user as a string
secondNumber = window.prompt( "Enter second integer",
i
// convert numbers from strings to integers
firstNumber = parselnt(firstNumber);
number2 = parselnt( secondNumber );
// add the numbers
sum = firstNumber + number2;
// display the results
document.writeln( "<H1>The sum is " + sum + "</H1>"
input/output
CRIPT TYPE="text/javascript">
“O");
صفحه 25:
Functions
<SCRIPT TYPE = “text/javascript">
var inputl = window.prompt( "Enter first number",
زر "مه
var input2 = window.prompt( "Enter second number",
زر "مه
var input3 = window.prompt( "Enter third number"
var valuel = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( valuel, value2, value3 );
document.writeln( "First number: " + valuel +
"<BR>Second number: " + value2 +
“<BR>Third number: " + value3 +
“<BR>Maximum is: " + maxValue );
// maximum method definition (called from above)
function maximum( x, y, z) { 25
صفحه 26:
Random Numbers
<SCRIPT TYPE="text/javascript">
var value;
document.writeln( "<H1>Random Numbers</H1>" +
"<TABLE BORDER = '1' WIDTH = '50%'><TR>" );
for (vari = 1; i <= 20; i++) {
value = Math.floor( 1 + Math.random() * 6 );
document.writeln( "<TD>" + value + "</TD>" );
if(i%5==0&&i!= 20)
document.writeln( "</TR><TR>" );
}
document.writeln( "</TR></TABLE>" );
</SCRIPT>
26
صفحه 27:
Roll the Die
<SCRIPT TYPE="text/javascript">
var frequency1 = 0, frequency2
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0, face;
// summarize results
for ( var roll = 1; roll <= 6000; ++roll ) {
face = Math.floor( 1 + Math.random() * 6 );
switch ( face ) {
case 1: ++frequency1; break;
case 2: ++frequency2; break;
case 3: ++frequency3; break;
case 4: ++frequency4; break;
case 5: ++frequency5; break;
case 6: ++frequency6; break;
1
1
document.writeln( "<TABLE BORDER = '1' WIDTH = '50%'>" ); ...27
0,
صفحه 28:
28
4 Rules of Craps
= First roll:
«7 0۲ 11 5 ۳
= 2,3, or 12 isa lose
= otherwise, roll becomes your point
= Subsequent rolls:
= rolling your point is a win
6 2 وا 11 0۲ 7 «
= otherwise continue to roll
صفحه 29:
Craps
<SCRIPT TYPE="text/javascript">
// variables used to test the state of the game
var WON = 0, LOST = 1, CONTINUE_ROLLING = 2;
// other variables used in program
var firstRoll = true, // true if first roll
sumOfDice = 0, // sum of the dice
myPoint = 0, // point if no win/loss on first roll
gameStatus = CONTINUE_ROLLING; // game not over yet
29
صفحه 30:
ess one roll of the dice
function play() {
if ( firstRoll ) {
// first roll of the dice
sumOfDice = rollDice();
switch ( sumOfDice ) {
case 7: case 11:
// win on first roll
gameStatus = WON;
document.craps.point.value = ""; // clear
point field
break;
case 2: case 3: case 12:
// lose on first roll
gameStatus = LOST;
document.craps.point.value = ""; // clear 30
صفحه 31:
Craps
default:
// remember point
gameStatus = CONTINUE_ROLLING;
myPoint = sumOfDice;
document.craps.point.value = myPoint;
firstRoll = false;
}
1
else {
sumOfDice = rollDice();
if ( sumOfDice == myPoint ) gameStatus = WON;
else if ( sumOfDice == 7 ) gameStatus = LOST;
}
31
صفحه 32:
Craps
if ( gameStatus == CONTINUE_ROLLING ) window.alert ("Roll again");
else {
if ( gameStatu: WON ) {
window.alert ("Player wins. " + "Click Roll Dice to play again.");
document.craps.point.value =
+
else {
window.alert ("Player loses. " + "Click Roll Dice to play again.");
document.craps.point.value = "";
firstRoll = true;
+
1
32
صفحه 33:
Craps
// roll the dice
function rollDice() {
var diel, die2, workSum;
diel = Math.floor( 1 + Math.random() * 6 );
die2 = Math.floor( 1 + Math.random() * 6 );
workSum = diel + die2;
document.craps.firstDie.value = die1;
document.craps.secondDie.value = die2;
document.craps.sum.value = workSum;
return workSum;
}
</SCRIPT>
33
صفحه 34:
Poker Hand
<SCRIPT TYPE="text/javascript">
function rand1toN(N) {
return Math.floor( 1+Math.random()*N );
1
function dealcard(card) {
Array(0,"A","2",
JQ" "K");
var suit ew Array(0, "Spades", "Hearts", "Diamonds", "Clubs");
card[0] ‘ank[rand1toN(13)];
card[1] = suit[rand1toN(4)];
}
34
صفحه 35:
Poker Hand
var card = new Array(2);
new Array(10);
new Array(10);
for (var i=0; i<=4; i++) {
dealcard(card);
player[i*2] = card[0];
player[i*2+1] = card[1];
dealcard(card);
dealer[i*2] = card[0];
dealer[i*2+1] = card[1];
35
صفحه 36:
Poker Hand
locument.writeln("<H1> PLAYER </H1>"
locument.writeln("<TABLE BORDER='1' >");
or (var i=0; i<=4; i++) {
document.writeln("<TR><TD><P>" + player[i*2] + "</TD>"
+ "<TD><P>" + player[i*2+1] + "</TD></TR>");
iocument.writeln("</TABLE> </HTML>");
</SCRIPT>
36
صفحه 37:
Character Processing
"text/javascript">
vars EBRA";
var S2 = "AbCdEfG";
Jocument.writeln( "<P> Character at index 0 in '"+
s+ 'is" + s.charAt( 0 ) );
Jocument.writeln( "<BR>Character code at index 0 in '" +
s+ "is" +s.charCodeAt( 0) + "</P>" );
Jocument.writeln( "<P>" + String.fromCharCode( 87, 79, 82, 68) +
™ contains character codes 87, 79, 82 and 68</P>" );
Jocument.writeIn( "<P>" + s2 + "' in lowercase is '" +
s2.toLowerCase() + "'" );
Jocument.writeln( "<BR>'" + s2 + "in uppercase is ' +
s2.toUpperCase() + "</P>" );
</SCRIPT>
37
صفحه 38:
Dates and Times
SCRI NGUAGE = "JavaScript">
r current = new Datet
ycument.writeln(current);
cument.writeln( "<H1>String representations and valueOf</H1>" );
cument.writeln( “toString: " + current.toString() +
"<BR>toLocaleString: " + current.toLocaleString() +
“<BR>toUTCString: " + current.toUTCString() +
"<BR>valueOf: " + current.valueOf() );
cument.writeln( "<H1>Get methods for local time zone</H1>" );
cument.writeln( “getDate: " + current.getDate() +
"<BR>getDay: " + current.getDay() + "<BR>getMonth: " +
current.getMonth() + "<BR>getFullYear: " + current.getFullYear() +
“<BR>getTime: " + current.getTime() + "<BR>getHours: " +
current.getHours() + "<BR>getMinutes: " + current.getMinutes() +
“<BR>getSeconds: " + current.getSeconds() + "<BR>getMilliseconds:
current.getMilliseconds() + "<BR>getTimezoneOffset: " +
current.getTimezoneOffset() );
38
صفحه 39:
Dates and Times
document.writeln( "<H1>Specifying arguments for a new
Date</H1>" );
var anotherDate = new Date( 1999, 2, 18, 1, 5, 3,9);
document.writeln( "Date: " + anotherDate );
document.writeln( "<H1>Set methods for local time
zone</H1>" );
anotherDate.setDate( 31 );
anotherDate.setMonth( 11 );
anotherDate.setFullYear( 1999 );
anotherDate.setHours( 23 );
anotherDate.setMinutes( 59 );
anotherDate.setSeconds( 59 );
document.writeln( "Modified date: " + anotherDate );
</SCRIPT>
39
صفحه 40:
4 Events
= JavaScript can execute a statement
(typically, call a function) when an event
occurs
=<... oneventname="javascript stmt;">
= <BODY ... ONLOAD="func();">
= <INPUT TYPE="submit" ...
ONSUBMIT="f();">
40
صفحه 41:
Events
onsubmit - call when submit button is clicked
onclick - call when this button is clicked
onreset - call when the reset button is clicked
onload - call after page loads
onmouseover - call when mouse pointer enters image area
onmouseout - call when mouse pointer leaves image area
onfocus - call when control receives focus
onblur - call when a control loses focus
onchange - call when a control loses focus and the value of its
contents has changed
many more
41
صفحه 42:
4 HTML Control
= JavaScript can change attr of Dom
« ۵
= getElementsByClassName
™ getElementsByName
= document.getElementByld(‘pld’).innerHT
ML=“My Name Is Masoud Tayefi”;
= document.getElementByld(‘inputld’).valu
ع6
42
صفحه 43:
HTML Control
name description
jetElementByld returns array of descendents
with the given tag, such
as "div"
getElementsByTagName returns array of descendents
with the given tag, such
as "div"
getElementsByName returns array of descendents
with the given name attribute
(mostly useful for accessing
form controls)
querySelector * returns the first element that
would be matched by the
given CSS selector string
querySelectorAll * returns an array of all
elements that would be
صفحه 44:
نی
= jQuery is a cross-platform
JavaScript library designed to
simplify the client-side scripting of
HTML
44
صفحه 45:
Include نی
=" <script src =
"https://code.jquery.com/jquery-
latest.min.js"> </script>
45
صفحه 46:
1 = We cannot use the DOM before the
page has been constructed. jQuery
gives us a more compatibile way to do
this.
= The DQMawWasrtoad = function() { // do stuff with the ]
* The diractiQuemaranslabion, // do stuff with the ا
= The jQuery Wayction() { // do stuff with the DOM });
صفحه 47:
۳۹ Dom Tree
صفحه 48:
jQuery Control
// id selector
var elem = $("#myid");
// group selector
var elems = $("#myid, p");
// context selector
var elems = $("#myid < div p");
// complex selector
var elems = $("#myid > hl.special:not(.classy)");
48
صفحه 49:
jQuery Selector
DOM method juery equivale
getElementByld("id") $("#id")
getElementsByTagName("tag" $/("tag")
)
getElementsByName("somena $("[name='somename']")
me")
querySelector("selector") $("selector")
querySelectorAll("selector") $("selector")
49
صفحه 50:
The jQuery object
= The $ function always (even for ID selectors)
returns an array-like object called a jQuery
object.
= The jQuery object wraps the originally
selected DOM objects.
= You can access the actual DOM object by
,, ¢aggessing the elements of the jQuery object.
document .getElementById("id") == $("#myid");
document.querySelectorAll("p") == $("p");
// true
document. getElementById("id") $("#myid") [0];
document. getElementById("id") $("#myid") .get (0);
document .querySelectorAll("p")[0] == $("p") [0];
50
صفحه 51:
DOM context identification
You can use querySelectorAll() and querySelector() on
any DOM object.
When you do this, it simply searches from that part of
the DOM tree downward.
Programmatic equivalent of a CSS context selector
var list = document .getElement sByTagName("ul") [0];
var specials = list.querySelectorAll('li.special');
سام ۳
صفحه 52:
۳۹ find / context parameter
= jQuery gives two identical ways
to do contextual element
vaidentification:
// These are identical
var specials = $("li.special", elem);
var specials = elem. find("li.special");
صفحه 53:
wae ves of DOM nodes
<p>
This is a paragraph of text with a
<a href="/path/page.html">lLink in it</a>.
</p>
This is a paragraph
node of text with a
53
صفحه 54:
the DOM tree وداج يق
name(s) description
۲ 5 start/end of this node's list
firstChild, lastChild of children
childNodes array of all this node's
children
nextSibling, neighboring nodes with
previousSibling the same parent
parentNode the element that contains
this node
54
صفحه 55:
55
Scripting
var x,y;
if (self.innerHeight) { // all except Explorer
x = self.innerWidth;
y = self.innerHeight; var x = $(window).width();
} vary =$
else if (document.documentélement && — (window).height();
document.documentElement.clientHeight) {
// Explorer 6 Strict Mode
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
1
else if (document.body) { // other Explorers
x = document.body.clientWidtt
y = document.body.clientHeight;
1
صفحه 56:
jQuery CSS Selectors
element {} = $('element')
#id {} = $(‘#id')
.class {} = $('.class')
56۱6610۲1, 56۱66100۳2 4 $('selector1, selector:
ancestor descendant « $(‘ancestor descendar
(0
(0
0 ae
parent > child {} ۰
snth-child() {} $
parent > child')
:nth-child(n)')
صفحه 57:
4 CSS Attribute Selectors
= $(‘input{name=firstname\\[\\]]')
= $('[title]') has the attribute
= $('‘Lattr="val"]') attr equals val
= $(‘Lattr!="val"]') attr does not equal val
= $(‘Lattr~="val"]') attr has val as one of
space-sep. vals
= $(‘Lattr*="val"]') attr begins with val
= $(‘Lattr$="val"]') attr ends with val
= $(‘Lattr*="val"]') attr has val anywhere
within
57
صفحه 58:
Custom Form Selectors
= $(‘div.myclass :checkbox')
= $(‘:input') <input>, <textarea>,
<select>, <button>
= $(‘:text') <input type="text">
= $(‘:radio') <input type="radio">
= $(':button') <input type="button">,
<button>
= $(':selected') <option selected="selected">
= etc.
58
صفحه 59:
Chaining
$('a').parent('li').siblings().find('a')
$('a').removeClass('old').addClass('new');
$('a').addClass('foo').parent('li').removeClass('foo')
var lis = $('.container li:first')
.addClass('first-li')
-next()
.addClass('second-li')
-end()
-NextALl()
.addClass(‘not-first-li')
-end(); // unnecessary; added for symmetry
59
صفحه 60:
60
//implicit
//explicit
melooping
$('li').removeClass('myclass');
$(‘li').each(function(index) {
$(this).append( ' #' + (index+1) );
1)
صفحه 61:
jQuery Samples
$('#textbox').hide();
var h1 = document.CreateElement("h1");
h1.innerHTML = "my text";
document.getElementsByTagName(‘body')[0].appendChild(h1);
$('body').append{( $("<h1/>").html("my text") ;
$(document).ready(function(){ //Script goes here });
$("h1.mainTitle")
$("h1.mainTitle#firstHeading")
61
صفحه 62:
Samples نی
Syntax: Examples:
° $('selector:first") ۰ $("p:first")
$("‘selector:last") $("p:last")
9 $(''selector:odd") 9 $(""p:odd")
9 5 ("معبع:ممخععاءو") 9 $("p:even")
59 $(‘selector:eq(i)") ® $("p:eq(1)")
© 4 0 جوم مهاه )("( © $cp:gt(t)")
۱ خا تسمه ("( © $epat(ay")
صفحه 63:
Samples دنر
Examples:
$("img").attr("src"
$("p").attr(“class",
"source"
$(“img").attr("“height",
calHt())
$(“img").attr({
“src : "/path/",
“title” : "My Img"
2:
$("div").removeAttr("class”
63
Syntax:
$('selector").attr("name"
$(‘selector").attr("key",
“val")
$('selector").attr("key",
fn)
$('selector").attr(propertie
s)
$("selector").removeAttr(a
ttr)
صفحه 64:
Event دنر
bind()
unbind()
ready()
toggle()
hover()
trigger()
* $(‘selector").bind(event, data, handler)
* $("selector").unbind(event, handler)
64
صفحه 65:
65
Event دنر
$(function(){
$('#myButton").bind("onelick", validate);
$(‘#myButton").click( validate);
»):
function validate(){
if( $('#myText").val().length == 0 ( )
alert("Error")
Jelse {
$("#myForm").submit();
}
صفحه 66:
66
ده
با تشكر از حوصله و تحمل شما
والسلام