Академический Документы
Профессиональный Документы
Культура Документы
JavaScript PDF
JavaScript PDF
qxd
22.02.2008
12:43
Page 1
JavaScript.
JavaScript ,
HTML.
(Document Object Model, DOM),
, DHTML JavaScript
. JavaScript
C, C++ Java,
. JavaScript
, , .
JavaScript
JavaScript. JavaScript,
,
. , ,
, , cookies
DHTML. IV V
API JavaScript, API API
W3C DOM, , , , ,
, API.
JavaScript
JavaScript 1.5 (ECMAScript v3). W3C DOM (Level 1
Level 2),
DOM Level 0.
, JavaScript.
, ,
, Internet Explorer 6, Netscape 6 Mozilla. ,
JavaScript .
.
, JavaScript, .
JavaScript .
(812) 3245353, (095) 9458100
OM
x D
Aja
5
JavaScript
ISBN13: 9785932861035
ISBN10: 5932861037
www.symbol.ru
9 785932 861035
David Flanagan
2008
JavaScript. ,
5
.
.
.
.
.
.
.
.
.
JavaScript. . . . : ,
2008. 992 ., .
ISBN10: 5932861037
ISBN13: 9785932861035
JavaScript.
. HTTP
Ajax, XML,
<canvas>, JavaScript,
, , , Flash
JavaScript Java.
I JavaScript. II
, .
, HTML,
DHTML,
,
Ajax, XPath XSLT XML,
Ajax. III Java
Script (, , , , ,
, JavaScript 1.5 ECMAScript v3). IV
JavaScript (API , DOM API Level 2
: XMLHttpRequest <canvas>).
ISBN10: 5932861037
ISBN13: 9785932861035
ISBN 0596101996 ()
, 2008
Authorized translation of the English edition 2006 OReilly Media, Inc. This trans
lation is published and sold by permission of OReilly Media, Inc., the owner of all
rights to publish and sell the same.
,
.
, , .
. 199034, , 16 , 7,
. (812) 3245353, www.symbol.ru. N 000054 25.12.98.
00593, 2; 953000 .
14.02.2008. 701001/16 . .
62 . . 2000 . N
199034, , 9 , 12.
,
.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.1. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.2. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.4. JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.5. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
I. JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.7. null . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.8. undefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.9. Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.11. Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.13. . . . . . . . . . . . . . . . . . 58
3.14. . . . . . . . . . . 60
3.15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
5.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5.9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6.3. if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.4. else if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
6.5. switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
6.6. while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
6.7. do/while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
6.8. for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
6.9. for/in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
6.10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
6.11. break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
6.12. continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
6.13. var . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
6.14. function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
6.15. return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
6.16. throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.17. try/catch/finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
6.18. with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
6.19. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
7.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
7.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
7.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
7.4. Object . . . . . . . . . . . . . . . . . . 127
7.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
7.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
7.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
7.8. , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
8.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
8.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
8.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
8.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
8.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
8.8. . . . . . . . . . . . . . . . . . . . . . . . . 156
8.9. Function() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9. , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
9.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
9.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
9.3. JavaScript . . . . . . . . . . . . . . . . . . . . . . 172
9.4. Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
9.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
9.8. : defineClass() . . . . . . . . . . . . . . . . . . . . . 194
10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
10.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
10.2. . . . . . . . . . . . . . . . . . . . . . . . . . . 204
10.3. . . . . . . . . . . . . . . . . . . . . . . . 208
11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
11.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
11.2. String . . . . . . . . . . . . . . . . . . . . 223
11.3. RegExp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
10
14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
14.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
14.2. Location History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
14.3. Window, Screen Navigator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
14.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
14.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
14.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
14.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
14.8. . . . . . . . . . . . . . . . . . . . . . . . 306
14.9. : . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
15.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
15.2. Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
15.3. DOM:
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
15.4. W3C DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
15.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
15.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
15.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
15.8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
15.9. : . . . . . . . . . . . . . . . . . . . . . 351
15.10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
15.11. IE 4 DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
11
17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
17.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
17.2. DOM Level 2 . . . . . . . 414
17.3. Internet Explorer . . . . . . . . . . . . . . . . . . . . . 425
17.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
17.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
17.6. onload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
17.7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
18. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
18.1. Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
18.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
18.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
18.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
12
22. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
22.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
22.2. CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
22.3. SVG . . . . . . . . . . . . . . . . . . . . . . 562
22.4. VML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
22.5. <canvas> . . . . . . . . . . . . . . . . . . . . . 572
22.6. Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
22.7. Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
JavaScript.
(Document Object Model, DOM),
(Application Pro
gramming Interface, API) JavaScript,
, , ,
. ,
(JavaScript 1.5),
.
JavaScript .
JavaScript , HTTP,
XML
. JavaScript
, .
Ajax Web 2.0.
, JavaScript, 8,
; ,
.
9. 10 ,
,
. ,
12 , JavaScript
Java. , JavaScript
Java 6, JavaScript Java
.
, JavaScript,
( 0) DOM W3C.
DOM ,
,
.
; :
19 Cookies
cookies
, .
14
20 HTTP , HTTP
, XMLHttpRequest,
Ajax .
21 JavaScript XML , JavaScript
, , , ,
, XML. ,
JavaScript, E4X.
22
JavaScript.
,
<canvas>.
,
SVG, VML, Flash Java.
23 Java Flash
Flash Java. ,
Flash Java.
III
JavaScript.
, API.
4 , .
,
(DOM API),
JavaScript.
, JavaScript.
Document ,
HTMLDocument .
DOM,
, . , NodeIterator
, . ,
DOM JavaScript
, .
, getComputedStyle()
AbstractView, Window, . JavaScript
, ,
AbstractView,
. ,
JavaScript, .
1 JavaScript.
. ,
1, JavaScript. 2 6
, , . .
,
:
15
2 .
3 ,
JavaScript.
4 ,
, .
5 JavaScript
,
. JavaScript
Java, , , C C++,
, ,
.
6
JavaScript. ,
C, C++ Java, , .
. JavaScript,
, , C
Java. JavaScript,
.
7 JavaScript.
8 , ,
, JavaScript.
9 ,
JavaScript.
,
. ,
JavaScript.
10 ,
JavaScript,
, .
11 ,
JavaScript
.
12 Java
JavaScript Java
, JavaScript, Java
, Java.
, Java.
II JavaScript .
JavaScript:
13 JavaScript JavaScript
.
Java
Script .
16
14
JavaScript Window ,
.
15 Document ,
JavaScript , .
.
16 CSS DHTML Java
Script CSS. , Java
Script , HTML,
, DHTML.
17
, ,
.
18 , HTML
.
15, ,
.
,
:
19 Cookies
. , HTTP
cookies Inter
net Explorer Flash.
20 HTTP ,
HTTP JavaScript, XMLHttpRequest
.
,
Ajax.
21 JavaScript XML , JavaScript
, , , XML
, .
22
JavaScript, .
,
SVG (Scalable Vector Graphics ) VML
(Vector Markup Language ), <canvas>
Flash Java.
23 Java Flash ,
JavaScript Java Flash
. , , JavaScript
Java Flash.
JavaScript. ,
.
17
.
, , FTP,
, .
JavaScript,
HTML ,
.
,
.
,
.
,
, OfficinaSansC.
.
.
,
. ,
,
.
OReilly.
.
.
,
. ,
ISBN. : JavaScript: The Definitive Guide, by David Fla
nagan. Copyright 2006 OReilly Media, Inc., 9780596101992.
permissions@oreilly.com.
, ,
:
18
OReilly Media
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 9989938 ( )
(707) 8290515 ()
(707) 8290104 ()
,
:
http://www.oreilly.com/catalog/jscript5
, , , :
http://www.davidflanagan.com/javascript5
:
bookquestions@oreilly.com
, ,
OReilly :
http://www.oreilly.com
Safari Enabled
Safari En
abled, , OReilly Net
work Safari Bookshelf.
Safari , .
,
, ,
, .
http://safari.oreilly.com.
19
JavaScript
JavaScript
. Java
Script C, C++ Java ,
if, while &&.
. JavaScript , . .
. JavaScript
.
Perl, C C++ Java.
JavaScript
, Self,
C++ Java. Perl, JavaScript
, ,
, Perl.
JavaScript
, , .
, .
JavaScript ,
, ,
. JavaScript
, HTML . ,
JavaScript, ,
, .
JavaScript
,
. JavaScript
, , ,
.
JavaScript
, JavaScript.
1.1. JavaScript
21
JavaScript
, .
,
JavaScript .
1.1. JavaScript
JavaScript .
JavaScript,
, .
1.1.2. JavaScript
JavaScript ,
, ,
,
, . ,
JavaScript ,
.
JavaScript ,
.
JavaScript
, , , ,
. , JavaScript
, ,
.
JavaScript,
. JavaScript,
,
.
1.2. JavaScript
, JavaScript
.
,
.
22
1. JavaScript
(European Computer Manufacturers Association, ECMA).1
JavaScript 1.5 Netscape
Mozilla Foundation, Jscript 5.5 Microsoft.
, Netscape 4.5 Internet Explorer 4,
.
, .
, ECMA262
ECMAScript.
, .
JavaScript , Net
scape Mozilla Foundation.
JavaScript.
JavaScript
. Firefox 1.5, Mozilla
Foundation, JavaScript 1.6.
() ,
7.7.10,
E4X, .
ECMA262,
JavaScript, ECMA ,
JavaScript, ECMA357.
JavaScript, E4X, ECMAScript for
XML.
XML ,
XML.
E4X JavaScript 1.6 Firefox 1.5.
E4X, 21
.
ECMA262, JavaScript 2.0.
,
.
JavaScript 2.0. ,
, Microsoft
JScript.NET, ActionScript 2.0 ActionScript 3.0,
Adobe ( Macromedia) Flash.
, Java
Script 2.0, JavaScript 1.6
. ,
, .
JavaScript 2.0 , ,
.
1
ECMA262, 3 ( http://www.ecma'internatio'
nal.org/publications/files/ecma'st/ECMA'262.pdf).
1.3. JavaScript
23
1.3. JavaScript
JavaScript ,
JavaScript. , ,
JavaScript, , JavaScript,
JavaScript. JavaScript
JavaScript,
JavaScript.
JavaScript JavaScript
(Document Object Model, DOM), .
JavaScript,
DOM
. , , JavaScript
.
JavaScript ,
DHTML ( 16), , Ajax ( 20).
13 JavaScript.
ECMA262 Java
Script, World Wide Web Consortium (W3C)
DOM, ,
. ( 15, 16 17
.) W3C DOM
Microsoft Internet Explorer;
.
1.3.1. JavaScript
, JavaScript,
JavaScript.
1.1 JavaScript,
, .
1.1. JavaScript
<html>
<head><title></title></head>
<body>
<h2> </h2>
<script>
var fact = 1;
for(i = 1; i < 10; i++) {
fact = fact*i;
document.write(i + "! = " + fact + "<br>");
}
</script>
</body>
</html>
, JavaScript,
, . 1.1.
24
1. JavaScript
, JavaScript HTML
<script> </script>. <script>
13. , ,
document.write().1 HTML
HTML .
JavaScript HTML
, . , JavaScript
:
.
JavaScript,
,
. 1.2 HTML,
, .
1.2. HTML' JavaScript
<button onclick="alert(' ');">
</button>
. 1.2 .
onclick 1.2 JavaScript, ,
. on
click alert(). . 1.2, alert()
.
1.1 1.2
JavaScript. ,
1
,
.
1.3. JavaScript
25
. 1.2. JavaScript
HTML. 1.3
JavaScript.
,
. ,
HTML, ,
.
. 1.3 HTML . ,
HTML .
. Java
Script :
, , JavaScript
, ,
.
HTML,
HTML. ,
. 1.3. JavaScript
26
1. JavaScript
onchange onclick .
,
, .
Java
Script calculate(). ,
calculate().
calculate() <script>.
,
, ,
<span>,
, id.
1.3 , .
JavaScript,
HTML, CSS JavaScript,
,
JavaScript.1
1.3. JavaScript
<html>
<head>
<title> JavaScript</title>
<style>
/* : */
.result { fontweight: bold; }
/* class="result"*/
#payment { textdecoration: underline; }
/* id="payment" */
</style>
</head>
<body>
<!
HTML,
JavaScript .
.
"loandata", ,
"interest" "years".
JavaScript, .
:
"onchange" "onclick".
JavaScript,
.
>
<form name="loandata">
<table>
<tr><td><b> :</b></td></tr>
<tr>
1
1.3. JavaScript
<td>1) ( ):</td>
<td><input type="text" name="principal" onchange="calculate();"></td>
</tr>
<tr>
<td>2) :</td>
<td><input type="text" name="interest" onchange="calculate( );"></td>
</tr>
<tr>
<td>3) :</td>
<td><input type="text" name="years" onchange="calculate( );"></td>
</tr>
<tr><td></td>
<td><input type="button" value=""
onclick="calculate( );"></td>
</tr>
<tr><td><b> :</b></td></tr>
<tr>
<td>4) :</td>
<td>$<span class="result" id="payment"></span></td>
</tr>
<tr>
<td>5) :</td>
<td>$<span class="result" id="total"></span></td>
</tr>
<tr>
<td>6) :</td>
<td>$<span class="result" id="totalinterest"></span></td>
</tr>
</table>
</form>
<script language="JavaScript">
/*
* JavaScript, .
* : calculate(),
* .
* <input> , , ,
* . <span>
*/
function calculate( ) {
// . ,
// .
// .
// .
var principal = document.loandata.principal.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
// .
var x = Math.pow(1 + interest, payments);
var monthly = (principal*x*interest)/(x1);
// <span> .
var payment = document.getElementById("payment");
var total = document.getElementById("total");
27
28
1. JavaScript
var totalinterest = document.getElementById("totalinterest");
// , .
// , <span>.
if (isFinite(monthly)) {
payment.innerHTML = monthly.toFixed(2);
total.innerHTML = (monthly * payments).toFixed(2);
totalinterest.innerHTML = ((monthly*payments)principal).toFixed(2);
}
// , ,
// , .
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
}
</script>
</body>
</html>
1.4. JavaScript
JavaScript ,
. JavaScript
. Netscape
JavaScript, JavaScript
. Internet Ex
plorer Microsoft JScript
IIS Windows Scripting Host. Adobe
JavaScript Flash
. Sun JavaScript
Java 6.0,
Java ( , , 12).
Netscape, Microsoft
JavaScript ,
. , Netscape,
Mozilla (http://www.mozilla.org/js/). Mozilla
JavaScript 1.5:
C SpiderMonkey, Java ,
, Rhino ().
,
JavaScript, , ,
. ,
, ,
.
1.5. JavaScript
29
1.5. JavaScript
. Java
Script . ,
.
JavaScript
. JavaScript , ,
,
. JavaScript,
.
,
, 1.1 :
<script>
document.write("<h2> </h2>");
for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){
document.write("Fibonacci (" + i + ") = " + fib);
document.write("<br>");
}
</script>
( ,
),
,
URL. ,
document.write().
JavaScript.
alert():
alert("Fibonacci (" + i + ") = " + fib);
, JavaScript
<html>, <head> <body> HTML.
JavaScript
URL javascript:
JavaScript . URL
(javascript:),
JavaScript (
). URL , Java
Script. URL
, .
,
JavaScript, URL
:
javascript:5%2
javascript:x = 3; (x < 5)? " x ": " x "
javascript:d = new Date(); typeof d;
javascript:for(i=0,j=1,k=0,fib=1; i<5; i++,fib=j+k,k=j,j=fib) alert(fib);
javascript:s=""; for(i in navigator) s+=i+":"+navigator[i]+"\n"; alert(s);
30
1. JavaScript
Firefox JavaScript,
.
, . Java
Script (javascript:) .
, JavaScript, ,
, . Java
Script :
, ,
, . ,
document.write() alert(). (
,
, 15.9.)
for/in ( 6).
, alert() ,
.
.
JavaScript
, , JavaScript. Internet Explo
rer Microsoft Script Debugger, Firefox
, Venkman.
,
, .
, , , , jslint;
JavaScript (http://
jslint.com).
JavaScript
2 12 Java
Script. ,
, , , ,
.
2
3
4
5
6
7
8
9 ,
10
11
12 Java
, , .
; , ,
, , .
JavaScript.
2.1.
JavaScript Unicode.
7 ASCII,
, 8 ISO Latin1,
, 16 Unicode
.
,
.
, ASCII
Latin1,
Unicode. ,
ASCII Latin1 Unicode, JavaScript
, ,
. , 8
, , , JavaScript
,
.
ECMAScript v3 Unicode
JavaScript. 1 2
Unicode ,
,
34
2.
2.2.
JavaScript , . ,
, ,
.
, while while, While
WHILE. online, Online, OnLine ONLINE
.
, , HTML, JavaScript,
. HTML JavaScript
. JavaScript
, HTML, .
HTML , JavaScript
. ,
onclick HTML onClick, Java
Script ( XHTML) onclick.
2.3.
JavaScript , ,
. ,
.
,
.
2.4.
JavaScript
(;), C, C++ Java.
. JavaScript ,
. ,
:
a = 3;
b = 4;
1
, )
,
; )
UTF16 (Unicode
,
, UTF8, UTF16 .); )
, . .
;
. . . .
2.5.
35
,
:
a = 3; b = 4;
, .
JavaScript
, JavaScript
.
, ,
, JavaScript ,
, , .
, ,
return, break continue ( 6). , ,
:
return
true;
JavaScript ,
:
return;
true;
, ,
return true;
, ,
, .
, :
break
outerloop;
JavaScript break,
.
++ (. 5)
, , .
2.5.
JavaScript, Java, C++, C.
, // ,
JavaScript.
/* */ .
C .
JavaScript:
// .
/* */ // .
/*
36
2.
* .
* .
*/
2.6.
, .
:
12
1.2
"hello world"
'Hi'
true
false
/javascript/gi
null
//
//
//
//
//
//
//
//
( )
ECMAScript v3 ,
. :
{ x:1, y:2 }
[1,2,3,4,5]
//
//
,
. JavaScript
3.
2.7.
. JavaScript
, .
Java .
, (_) ($).1
, ,
. ( , . .
.) :
i
my_variable_name
v13
_dummy
$str
ECMAScript v3
Unicode. JavaScript
ASCII. ECMAScript v3
1
$ , Java
Script 1.1. ,
.
37
2.8.
2.8.
JavaScript .
( , ) Java
Script. . 2.1 ,
ECMAScript v3. JavaScript
, . . .
2.1. JavaScript
break
do
if
switch
typeof
case
else
in
this
var
catch
false
instanceof
throw
void
continue
finally
new
true
while
default
for
null
try
with
delete
function
return
. 2.2 . Java
Script , ECMAScript v3
.
2.2. , ECMA
abstract
double
goto
native
static
Boolean
enum
implements
package
super
byte
export
import
private
synchronized
char
extends
int
protected
throws
class
final
interface
public
transient
const
float
long
short
volatile
debugger
ECMAScript v4
as, is, namespace use. JavaScript
,
.
38
2.
,
, JavaScript.
,
(
), ,
, . . 2.3
,
ECMAScript v 3.
, ,
JavaScript (, )
.1
2.3. ,
arguments
encodeURI
Infinity
Object
String
Array
Boolean
Error
isFinite
parseFloat
SyntaxError
escape
isNaN
parseInt
TypeError
Date
eval
Math
RangeError
undefined
decodeURI
EvalError
NaN
ReferenceError
unescape
decodeURIcomponent
Function
Number
RegExp
URIError
Window
, JavaScript.
, (values),
3,14 Hello World. ,
,
(data types),
. Java
Script : ,
( )
( ). JavaScript
, null undefined,
.
JavaScript
, (object). (. .
) ( ,
, , ).
JavaScript :
.
(array). JavaScript
, ,
.
JavaScript , '
(function). , .
(invoked) .
, , , Java
Script .
.
JavaScript
.
, (classes) . Date
, , RegExp ,
40
3.
( , 11),
Error ,
, JavaScript.
. ,
, 7 8. ,
Date, RegExp Error, III
. ,
.
3.1.
, . JavaScript
, C Java, ,
. JavaScript
64 (
), IEEE 754.1
1,7976931348623157 10308 5 10324.
, JavaScript,
. JavaScript
, . :
(),
.
(. 5),
.
3.1.1.
JavaScript
. :
0
3
10000000
JavaScript
9007199254740992 (253) 9007199254740992 (253) .
. , JavaScript (
, 5) 32
, 2147483648 (231) 2147483647 (2311).
3.1.2.
JavaScript
( 16).
0x 0X,
1
Java double.
double C C++.
41
3.1.
. 0 9
a ( A) f ( F), 10 15.
:
0xff
// 15*16 + 15 = 255 ( 10)
0xCAFE911
ECMAScript
( 8), JavaScript
. 0,
, 0 7. :
0377
,
, ,
,
.
3.1.3.
;
.
,
.
: , e ( E),
.
, 10 ,
.
:
[][.][(E|e)[(+|)]]
:
3.14
2345.789
.333333333333333333
6.02e23
// 6.02 X 1023
1.4738223E32
// 1.4738223 X 1032
: ,
JavaScript
( 18437736874454810627). ,
JavaScript
. , ,
.
3.1.4.
JavaScript
,
42
3.
:
hypot = Math.sqrt(x*x + y*y);
, Java
Script, Math
.
3.1.5.
JavaScript
.
3.2.
3.1.6.
JavaScript .
,
, Java
Script Infinity.
,
, Infinity.
JavaScript,
(, )
.
, NaN. (NotaNumber)
: , !
isNaN(). , isFinite(),
NaN / .
. 3.1 , JavaScript
.
3.1.
Infinity
NaN
Number.MAX_VALUE
43
3.2.
Number.MIN_VALUE
( )
Number.NaN
Number.POSITIVE_INFINITY ,
Number.NEGATIVE_INFINITY ,
3.2.
, ,
Unicode JavaScript
. ,
,
. : JavaScript ,
char C, C++ Java.
.
3.2.1.
Unicode
, (' ").
,
, ,
.
.
,
\n, .
:
""
// :
'testing'
"3.14"
'name="myform"'
" O'Reilly, ?"
" \n "
" "
, ECMAScript v1
Unicode . ,
, JavaScript 1.3,
ASCII Latin1. , Unicode
. ,
Unicode.
: ,
,
44
3.
,
, , can't O'Reilly's.
,
(\) , (
).
JavaScript HTML, HTML
, , JavaScript. JavaScript,
HTML ,
. JavaScript HTML
JavaScript, HTML.
JavaScript
, , ,
HTML :
<a href="" onclick="alert('')"> </a>
3.2.2.
(\) JavaScript.
, , ,
. , \n '
(escape sequence), .1
, ,
\', .
, . ,
.
, :
'You\'re right, it can\'t be a quote'
. 3.2
. ;
Latin1 Unicode .
, \xA9 ,
Latin1 A9.
, \u, Unicode
, . , \u03c0
. ,
Unicode ECMAScript v1,
, JavaScript 1.3.
JavaScript Latin1
, ,
1
, C, C++ Java,
JavaScript .
45
3.2.
ECMAScript v3 .
3.2. JavaScript
\0
NUL (\u0000)
\b
(\u0008)
\t
(\u0009)
\n
(\u000A)
\v
(\u000B)
\f
(\u000C)
\r
(\u000D)
\"
(\u0022)
\'
(\u0027)
\\
(\u005C)
\xXX
Latin1, XX
\uxXXXX
Unicode, XXXX
\XXX
Latin1,
XXX, 1 377. ECMAScript v3;
, ,
( JavaScript
)
. \ ,
. 3.2, (
, ,
). , \# , #.
3.2.3.
JavaScript
. + , ,
, ,
. :
msg = "Hello, " + "world";
// "Hello, world"
greeting = " ," + " " + name;
length. , s ,
:
s.length
.
s:
46
3.
last_char = s.charAt(s.length 1)
, s,
:
sub = s.substring(1,4);
a s :
i = s.indexOf('a');
, .
String
.
, JavaScript (,
, JavaScript) , 0.
, . ,
C, ++ Java, ,
, ,
, .
JavaScript
( ) ,
charAt()
:
last_char = s[s.length 1];
ECMAScript v3,
.
, ,
,
. , .
JavaScript.
, .
, .
3.2.4.
,
. , ,
:
var n = 100;
var s = n + " .";
JavaScript
,
: ,
:
var n_as_string = n + "";
String():
var string_value = String(number);
47
3.2.
toString():
string_value = number.toString( );
toString() Number (
Number, )
, ,
, .
, 10.
( 2 36)1, :
var n = 17;
binary_string = n.toString(2);
// "10001"
octal_string = "0" + n.toString(8); // "021"
hex_string = "0x" + n.toString(16); // "0x11"
JavaScript, Java
Script 1.5,
, ,
.
,
.
ECMAScript v3 JavaScript 1.5
Number. to
Fixed()
.
. toExponential(),
.
toPrecision().
,
. :
. :
var n = 123456.789;
n.toFixed(0);
n.toFixed(2);
n.toExponential(1);
n.toExponential(3);
n.toPrecision(4);
n.toPrecision(7);
1
//
//
//
//
//
//
"123457"
"123456.79"
"1.2e+5"
"1.235e+5"
"1.235e+5"
"123456.8"
ECMAScript
toString(),
, ,
10. ,
.
.
48
3.
3.2.5.
,
. , :
var product = "21" * "2";
// 42.
; 0:
var number = string_value 0;
( :
.)
Number() :
var number = Number(string_value);
.
,
,
.
parseInt() par
seFloat(). ,
, ,
. parseInt()
, parseFloat() ,
. 0x 0X, par
seInt() .1 :
parseInt("3 ");
parseFloat("3.14 ");
parseInt("12.34");
parseInt("0xFF");
//
//
//
//
3
3.14
12
255
parseInt()
. 2
36, :
parseInt("11", 2);
parseInt("ff", 16);
parseInt("zz", 36);
parseInt("077", 8);
parseInt("077", 10);
1
//
//
//
//
//
3 (1*2 + 1)
255 (15*16 + 15)
1295 (35*36 + 35)
63 (7*8 + 7)
77 (7*10 + 7)
ECMAScript , 0 (
0x 0X), parseInt()
, .
, parseInt()
, 0,
.
3.3.
49
parseInt() parseFloat()
, NaN:
parseInt("eleven");
// NaN
parseFloat("$72.47"); // NaN
3.3.
. , ,
, true false.
, . . ,
.
,
JavaScript. :
a == 4
, a 4. ,
true. a
4, false.
JavaScript. , if/else JavaScript
, true, , false.
, ,
, . :
if (a == 4)
b = b + 1;
else
a = a + 1;
, a 4. ,
b 1; 1
a.
true false, (true)
(false) (true) (false).
3.3.1.
,
.1
1
, C, , JavaScript
, C,
. Java
, JavaScript , ,
boolean Java JavaScript
, ,
, JavaScript C, Java.
50
3.
, true
1, false 0.
, true "true", false "false".
,
true, 0 NaN,
false.
, true, ,
false.
null undefined false, ,
, null, true.
,
Boolean():
var x_as_boolean = Boolean(x);
:
var x_as_boolean = !!x;
3.4.
, JavaScript
JavaScript.
, JavaScript
. , ,
,
; ,
. JavaScript
, Math.sin(), .
JavaScript ,
, , :
function square(x) // square. , x.
{
// .
return x*x;
//
// .
}
// .
, , ,
,
. :
y = Math.sin(x);
y = square(x);
d = compute_distance(x1, y1, z1, x2, y2, z2);
move();
JavaScript ,
, JavaScript. ,
Java, ,
: . ,
3.5.
51
JavaScript ,
. , ,
, .
. ,
8.
, ,
, .
(
3.5), .
. 7.
3.4.1.
square().
JavaScript
. ECMAScript v3 (
JavaScript 1.2 )
. func
tion, ,
, , .
, ,
, , .
, JavaScript
. square() :
function square(x) { return x*x; }
:
var square = function(x) { return x*x; }
, , .
LISP,
.
, , ,
.
:
Function(). :
var square = new Function("x", "return x*x;");
.
, JavaScript ,
, , ,
.
3.5.
, '
(properties) . ( ,
52
3.
.)
, , . ,
image width height,
:
image.width
image.height
JavaScript
, , .
JavaScript:
document.myform.button
button , , ,
myform document.
, , ,
, .
,
() . , write() document
:
document.write(" ");
JavaScript , . .
.
: , ,
. image, ,
:
image["width"]
image["height"]
;
. ,
7.
3.5.1.
7,
. :
var o = new Object();
var now = new Date();
var pattern = new RegExp("\\sjava\\s", "i");
,
:
var point = new Object();
point.x = 2.3;
point.y = 1.2;
3.6.
53
3.5.2.
JavaScript ,
. (
)
/, .
. , point
:
var point = { x:2.3, y:1.2 };
. :
var rectangle = { upperLeft: { x: 2, y: 2 },
lowerRight: { x: 4, y: 4 }
};
,
JavaScript.
,
:
var square = { "upperLeft": { x:point.x, y:point.y },
'lowerRight': { x:(point.x + side), y:(point.y+side) }};
3.5.3.
,
true.
, toString()
, .
, valueOf().
,
.
valueOf() .
toString(),
.
, .
3.6.
(array), , .
, , ,
, . JavaScript
, , .
, a , i , a[i]
. , . . a[2]
a.
JavaScript,
. :
54
3.
document.images[1].width
width ,
, images document.
:
(. 3.5). ,
.
. , JavaScript
(
). , JavaScript ,
,
, Java. 7.
3.6.1.
Array().
:
var a = new Array();
a[0] = 1.2;
a[1] = "JavaScript";
a[2] = true;
a[3] = { x:1, y:3 };
Array(). ,
:
var a = new Array(1.2, "JavaScript", true, { x:1, y:3 });
Array() ,
. , 10
:
var a = new Array(10);
3.6.2.
JavaScript
. , ,
, .
, .
, ,
, :
var a = [1.2, "JavaScript", true, { x:1, y:3 }];
, :
var matrix = [[1,2,3], [4,5,6], [7,8,9]];
,
:
var base = 1024;
var table = [base, base+1, base+2, base+3];
3.7. null
55
,
.
, :
var sparseArray = [1,,,,5];
3.7. null
null JavaScript . ,
null .
null . null,
, , , ,
.1
null ,
false, 0,
"null".
3.8. undefined
, JavaScript, undefined.
, ,
, ,
. , undefined
, null.
null undefined ,
== . :
my.prop == null
, my.prop ,
, null. null undefined
, ,
. null
undefined, === typeof (
5).
null, undefined
JavaScript. ECMAScript v3 ,
undefined,
undefined. , , , un
defined ,
.
,
undefined, :
var undefined;
1
56
3.
, , ,
undefined. void (. 5)
undefined.
undefined ,
false. NaN,
"undefined".
3.9. Date
,
JavaScript.
, JavaScript ,
,
. Date JavaScript new
Date() ( new 5, 7
):
var now = new Date(); // , .
// , .
// : , 11!
var xmas = new Date(2000, 11, 25);
Date
, (GMT). :
xmas.setFullYear(xmas.getFullYear() + 1); // .
var weekday = xmas.getDay();
// 2007 .
document.write(": " + now.toLocaleString()); // .
Date ( ,
Date) ,
, ,
.
Date .
3.10.
.
. JavaScript
Perl.
JavaScript RegExp
RegExp(). Date, RegExp
JavaScript;
,
JavaScript.
Date, RegExp
JavaScript.
.
57
3.11. Error
,
. :
/^HTML/
/[19][09]*/
/\bjavascript\b/i
11.
, Java
Script.
3.11. Error
ECMAScript v3 .
JavaScript
. (
6 throw try.)
message,
.
Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError URIError.
.
3.12.
,
,
. :
, ,
JavaScript . ,
, ,
. ,
.
, JavaScript . . 3.3
, ,
.
3.3.
"undefined"
NaN
false
Error
null
"null"
false
Error
true
NaN
String
false
String
"0"
false
Number
NaN
"NaN"
false
Number
58
3.
3.3 ()
Infinity
"Infinity"
Infinity
"Infinity"
true
Number
true
Number
true
Number
Boolean
true
"true"
false
"false"
Boolean
toString()
valueOf(),
toString() NaN
true
3.13.
,
:
.1 ,
:
var s = "These are the times that try people's souls.";
var last_word = s.substring(s.lastIndexOf(" ")+1, s.length);
, , s ,
.
?
? typeof (. 5) ,
, .
?
,
. ,
JavaScript Number, String Boolean.
.
(wrapper) ,
,
.
JavaScript .
, . .
, JavaScript
. String .
,
1
,
.
3.13. *
59
. , ,
;
, .
, String,
, ,
, ,
. , s ,
:
var len = s.length;
s , .
String, length,
, s.
, ,
. JavaScript
, .
String ,
, . String
, , new. :
var s = "hello world";
//
var S = new String("Hello World"); // String
S String? ,
.
typeof, , S ,
, ,
String.1 ,
String, . , .
String ,
, JavaScript String .
, String +,
:
msg = S + '!';
, ,
String,
Number Boolean.
.
, , ,
Object():
var number_wrapper = Object(3);
eval() String
, String
, , .
60
3.
3.14.
, 3.5.3.
.1
,
true.
( ), ,
,
false. ,
true :
new
new
new
new
. 3.3 ,
valueOf().
valueOf() Object,
. valueOf()
, JavaScript
toString()
.
.
toString()
,
. , ,
0! ,
, n,
n, n.
, NaN.
,
. ,
. + (<, <=, > >=)
, , ,
, :
.
JavaScript valueOf().
( , ),
. valueOf()
, JavaScript
toString().
1
,
.
3.15.
61
: +
Date, toString().
, Date
toString() valueOf(). Date
+,
,
, .
valueOf(),
.
+,
. , ,
, .
, valueOf(),
. valueOf(), ,
,
, valueOf() ,
toString() .
, valueOf().
, , valueOf() toNumber().
, ,
;
valueOf() .
3.15.
JavaScript, ,
.1
. , .
.
, , .
,
.
: '
.
, ,
. ,
,
.
, .
, , .
,
. ,
,
1
,
.
62
3.
( ,
).
.
,
.1
, , .
,
. ,
, .
,
.
.
,
. , .
,
.
. ,
, , ,
. ,
(. . ), .
,
. . 3.4
. ,
, ,
.
, Java
Script. ,
, .
3.4.
.
.
,
.
.
,
.
.
.
C , ,
. ,
JavaScript .
63
3.15.
( ),
,
.
,
,
.
,
.
3.15.1.
JavaScript : '
, ,
, .
JavaScript. ,
,
JavaScript.
.
.
,
, ,
.
,
.
? ,
.
JavaScript
, .
.
.
,
,
. ,
. 3.1 ,
. ,
, .
3.1. ,
//
var n = 1; // n 1
var m = n; // : m 1
//
// , ,
function add_to_total(total, x)
{
total = total + x; // total
}
// , ,
// n m. n
// total. m n,
64
3.
// n.
// n .
// , .
add_to_total(n, m);
//
//
//
//
//
if
.
1
, "" .
, n. ,
, .
(n == 1) m = 2; // n , 1;
// m 2
3.2. ,
.
, .
Date,
.
3.2. ,
// , 2007
// xmas ,
var xmas = new Date(2007, 11, 25);
// ,
var solstice = xmas; //
//
solstice.setDate(21);
//
xmas.getDate( ); // 21, 25
// .
// .
// , .
// ,
// , .
function add_to_totals(totals, x)
{
totals[0] = totals[0] + x;
totals[1] = totals[1] + x;
totals[2] = totals[2] + x;
}
// , .
// , , ,
// ,
// , :
(xmas == solstice) // true
// , , ,
// .
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);
// " "
3.15.
65
// !
(xmas != solstice_plus_4) // true
, .
.
,
.
. ,
, .
, . ,
, ,
, ,
, . 3.3 .
3.3.
// add_to_totals(). ,
// .
function add_to_totals2(totals, x)
{
newtotals = new Array(3);
newtotals[0] = totals[0] + x;
newtotals[1] = totals[1] + x;
newtotals[2] = totals[2] + x;
totals = newtotals; //
//
}
3.15.2.
,
. ,
, .
,
.
,
. ,
, .
,
JavaScript
. ,
,
, .
: JavaScript
. charAt(),
, setCharAt(),
. . JavaScript
66
3.
JavaScript ,
.
, , . .
,
. ,
JavaScript , ,
,
.
3.15.3.
, ,
,
JavaScript, ,
. 3.4
, .
3.4. , ?
// , , ,
// . ,
// .
// , ,
// , :
var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2) document.write(" ");
, .
,
C, C++ Java,
.
. Java
Script ,
, ,
. , ,
JavaScript ()
, .
3.15.4. :
3.5 ,
JavaScript.
3.5. JavaScript
, . ,
, , .
. , JavaScript
2 i:
i = 2;
3 i
sum:
var sum = i + 3;
, .
JavaScript ,
! ,
, , ,
/.1
4.1.
JavaScript , Java C,
, JavaScript (untyped) .
, , JavaScript
, Java C,
, . , JavaScript
, :
i = 10;
i = "";
1
,
.
5, 6 7, .
68
4.
Java, C, C++
.
JavaScript, , ,
. ,
, JavaScript ,
.
3.
JavaScript
, C++ Java,
, ,
,
. JavaScript
, ,
.
4.2.
JavaScript, .1
var :
var i;
var sum;
:
var i, sum;
, :
var message = "hello";
var i = 0, j = 0, k = 0;
var,
, (undefined),
.
, var for
for/in ( 6),
. :
for(var i = 0; i < 10; i++) document.write(i, "<br>");
for(var i = 0, j = 10; i < 10; i++, j) document.write(i*j, "<br>");
for(var i in o) document.write(i, "<br>");
, var, '
(permanent): delete
. ( delete 5.)
,
JavaScript.
4.3.
69
4.2.1.
var
. ,
.
, JavaScript
. ,
var, JavaScript
. , ,
, .
( ),
,
var . var
, . (
.)
4.3.
(scope) ,
.
JavaScript. ,
, . '
.
, .
.
, ,
. ,
:
var scope = "";
function checkscope() {
var scope = "";
document.write(scope);
}
checkscope();
//
//
// ,
// ""
, var
, .
, , :
scope = "";
function checkscope() {
scope = "";
document.write(scope);
myscope = "";
document.write(myscope);
}
checkscope();
document.write(scope);
document.write(myscope);
// , var
//
//
//
//
// ""
// ""
// ""
70
4.
, , ,
. ,
, ,
. ,
: var.
.
,
. :
var scope = " ";
//
function checkscope() {
var scope = " ";
//
function nested() {
var scope = " "; //
//
document.write(scope); // " "
}
nested();
}
checkscope();
4.3.1.
: C, C++ Java, JavaScript
. , ,
, , .
i, j k :
. ,
C, C++ Java:
function test(o) {
var i = 0;
// i
if (typeof o == "object") {
var j = 0;
// j ,
for(var k = 0; k < 10; k++) { // k ,
document.write(k);
}
document.write(k);
// k : 10
}
document.write(j);
// j ,
}
, , ,
, . :
var scope = "";
function f() {
alert(scope);
// "undefined", "".
var scope = ""; // ,
// .
alert(scope);
// ""
}
f();
, alert()
, . . var,
4.4.
71
, .
.
, ,
. ,
var . f
:
function f() {
var scope;
alert(scope);
scope = "";
alert(scope);
}
//
//
//
//
, undefined
,
.
4.3.2.
JavaScript: .
, . '
.
, .
,
.
, ,
.
, undefined.
(unassigned),
, .
:
var x;
// . undefined.
alert(u); // .
u = 3;
// .
4.4.
, , .
, .
? , , ,
, JavaScript.
: .
, , null undefined
. , .
. ,
, .
72
4.
. Java
Script ,
.1
. ,
.
: .
JavaScript.
,
, .
.
. ,
, .
, . .
. ,
( ):
var a = 3.14;
var b = a;
a = 4;
alert(b)
//
//
//
//
3.14;
. , ,
, ( ):
var a = [1,2,3];
var b = a;
a[0] = 99;
alert(b);
//
//
//
//
,
[99,2,3],
, ,
. , ,
. ,
,
.
; .
,
.
,
.
3.15.
, , JavaScript
. .
, ,
. ,
JavaScript ,
.
. , ,
1
,
JavaScript.
4.5.
73
, , . . :
. ,
, ,
. , , ,
, ,
, .
4.5.
; ,
. ,
.
,
. .
, ,
,
. JavaScript , ,
. ,
, ,
JavaScript , .
, C C++, .
,
, ( ).
.1
JavaScript, , ,
(garbage collection). JavaScript
, .
, (. .
), , ,
.2 :
var s = "hello";
//
var u = s.toUpperCase(); //
s = u;
//
"hello"
.
.
1
: ( ) ,
, ,
.
STL, .
,
new delete. . . .
, ,
.
Perl; . . . . .
74
4.
.
, ,
, , .
4.6.
, JavaScript
. ,
JavaScript . .
i i o? : .
JavaScript .
4.6.1.
, JavaScript
, .
JavaScript
. JavaScript ,
.
JavaScript ,
. , Infini
ty, parseInt Math ,
parseInt() Math.
.
(. . JavaScript, )
this.
this , 8.
JavaScript Java
Script, ,
Window. window,
, this
. Window ,
parseInt Math, ,
navigator screen.
4.6.2.
,
?
. (call object).
,
.
JavaScript
.
4.6.3. JavaScript
, JavaScript
(execution context), . . ,
4.7.
75
JavaScript. ,
. JavaScript,
, ,
. JavaScript
, .
, JavaScript
.1
(
.) JavaScript,
. JavaScript
.
, . , JavaScript
pa
rent.frames[1], x
parent.frames[0].x.
,
JavaScript.
JavaScript
13. , JavaScript
JavaScript
.
. JavaScript
, ,
. Java
Script. , A
, B
. ,
B A.
, , .
, JavaScript
,
, . 13.8.
4.7.
,
JavaScript:
, ,
, .
1
; ,
.
76
4.
, , ,
. , ,
,
,
.
, JavaScript.
JavaScript '
(scope chain), , , .
JavaScript x (
), (
) .
x, .
x, JavaScript
. x,
, . .
JavaScript ( ,
),
. .
, undefined. ( )
.
, (
), ( ).
.
. 4.1.
. 4.1.
, JavaScript.
, C, C++ Java, , JavaScript
, . ,
C, C++ Java, ,
JavaScript.
5.1.
JavaScript,
.
, :
1.7
"JavaScript is fun!"
true
null
/java/
{ x:2, y:2 }
[2,3,5,7,11,13,17,19]
function(x){return x*x;}
i
sum
//
//
//
//
//
//
//
//
//
//
null
i
sum
.
, ,
, .
.
( ) . ,
, 1.7 , i .
:
i + 1.7
78
5.
. + ,
. (),
. :
(i + 1.7) sum
sum , i + 1.7.
, JavaScript ,
+ .
5.2.
C, C++ Java, JavaScript
. . 5.1,
. :
, + =,
, delete instanceof. ,
,
.
, P,
, , A, ( L
, R ). , , ,
,
.
5.1. JavaScript'
P
15 L
[]
()
14 R ++
()
R
()
R
( )
R +
( )
R ~
()
R !
()
R delete
()
R typeof
()
R new
79
5.2.
R void
()
13 L
*, /, %
, ,
12 L
+,
11 L
<<
>>
>>>
10 L
<, <=
>, >=
instanceof
in
==
!=
===
!==
&
&&
||
R ?:
,
,
R =
5.2.1.
. JavaScript, +,
, .
, . ,
. JavaScript ,
80
5.
, .
3 ,
3. , JavaScript ,
?:, .
5.2.2.
JavaScript,
, , , .
,
. , ,
"a" * "b" JavaScript. Java
Script
, "3" * "5" .
15, "15". JavaScript
3.12.
.
+,
. ,
,
. , "1" + 0 "10".
, , ,
(lvalue).
, ,
. Java
Script ,
. ECMAScript
,
, .
, ,
. (, , . .)
,
, , . ,
a < 3 true, a
, 3. , ,
, if, while for,
JavaScript
.
5.2.3.
. 5.1 , P,
. ,
. P
, , .
:
w = x + y * z;
5.3.
81
*
+, . ,
= ,
.
.
, :
w = (x + y)* z;
, ,
.
: ,
.
5.2.4.
. 5.1 , A,
. L , R
.
.
, . ,
,
:
w = x + y + z;
w = ((x + y) + z);
( ) :
x = ~~y;
w = x = y = z;
q = a?b:c?d:e?f:g;
:
x = ~((~y));
w = (x = (y = z));
q = a?b:(c?d:(e?f:g));
, ,
.
5.3.
, ,
.
:
(+)
. ,
.
82
5.
, .
valueOf() / toString().
()
,
.
, .
(*)
* .
.
(/)
/ .
. , ,
,
. Java
Script ,
. 5/2 2.5, 2.
, 0/0 NaN.
(%)
% ,
. ,
.
, 5 % 2 1.
, .
, 4.3 % 2.1 0.1.
()
,
.
, ,
. ,
.
(+)
JavaScript
.
, ,
:
var profit = +1000000;
;
.
. , NaN.
(++)
(. . )
, ,
. ,
,
5.4.
83
.
. (
), 1,
. (
), 1,
.
,
. , i j 2:
i = 1;
j = ++i;
i 2, j 1:
i = 1;
j = i++;
, . :
, JavaScript
. , JavaScript
.
()
(. . 1)
, ,
. ,
,
. ++,
. ,
,
, .
5.4.
. ,
(true
false) . 6,
if for
.
84
5.
ECMAScript v3 Java
Script 1.3 .
JavaScript =, == ===. ,
, .
! ,
= , ,
== , ===.
JavaScript , '
. , ==
=== , . ,
, .
, , .
, .
, ,
. ,
. ,
, , ,
, .
,
,
. (
, ,
.)
===
:
, .
, ,
NaN ( ,
). NaN
, ! ,
NaN, isNaN().
, .
, . ,
Unicode
. Java
Script , ,
.
III
String.localeCompare().
true false,
.
, ,
. (
), ,
.
5.4.
85
null undefined, .
==:
,
. , ; ,
.
,
. :
null, undefined, .
, ,
.
true, 1
. false,
0 .
,
,
.
toString(), valueOf().
JavaScript
valueOf(), toString(), Date,
toString(). ,
JavaScript,
, .
.
:
"1" == true
true, . .
. true 1,
. "1" 1.
, true.
86
5.
5.5.
JavaScript. ,
(
) true false ,
. 6,
if while .
5.5.1.
.
:
(<)
< true, ,
; false.
(>)
> true, ,
; false.
(<=)
<= true,
; false.
(>=)
>= true,
; false.
.
, ,
, .
:
,
.
,
.
,
,
.
, NaN
false. ( JavaScript 1.1
NaN, .)
, ,
JavaScript . , ,
Date , . .
, .
,
false.
87
5.5.
NaN,
false.
, ,
Unicode.
Unicode
, JavaScript
; ,
. :
, . . Unicode (
, ASCII)
. . ,
< "Zoo" "aardvark".
String.localeCompare(),
.
String.toLowerCase() String.toUpperCase().
<= ( ) >= ( )
.
,
. ,
NaN (
); false.
5.5.2. in
in ,
. ( ).
true,
, . :
var
var
var
var
var
//
//
//
//
//
true
true
false;
; true
5.5.3. instanceof
instanceof , ,
. true, ,
, , ;
false. 9 , JavaScript
.
, instanceof
. :
Object. :
var d = new Date(); // Date()
d instanceof Date; // true; d
// Date()
88
5.
d instanceof Object; //
//
d instanceof Number; //
var a = [1, 2, 3]; //
a instanceof Array; //
a instanceof Object; //
a instanceof RegExp; //
true;
Object
false; d Number
true; a
true;
false;
instanceof
, , instanceof false.
,
.
5.6.
, ,
, .
+ .
, , ,
. , "hello there":
"hello" + " " + "there"
"22":
a = "2"; b = "2";
c = a + b;
//
//
//
//
//
. 3.
. "12".
; 2 "2". "12".
. false.
. true.
5.7.
89
, , +
, . ,
, .
:
s = 1 + 2 + " "; // "3 "
t = " : " + 1 + 2; // " : 12"
,
+ , .
, :
s = (1 + 2) + " "; // ;
t = (" : " + 1) + 2; //
5.7.
.
if, while for.
5.7.1. (&&)
&&
: true ,
true.
false, false.
.
.
false ( null, 0, "" undefined),
.
.1
,
, .
, &&. ,
JavaScript :
if (a == b) stop();
(a == b) && stop();
( Perl)
,
. , ,
. :
1
90
5.
if ((a == null) && (b++ > 10)) stop();
, , , . .
,
false. ,
, (, ,
), &&,
, .
,
.
, ,
, .
5.7.2. (||)
||
: true,
( ) true. false,
false.
||
, , &&, .
.
true, .
.1
&&, ,
,
, .
|| ,
, . .
.
, ||
, , ,
, .
, ||
, null (. .
, true).
:
// max_width , .
// preferences.
// ( max_with) ,
// , .
var max = max_width || preferences.max_width || 500;
5.8.
91
5.7.3. (!)
! ,
. . ,
a true ( ,
true), !a false. p && q
false ( , false), !(p && q) true.
,
, : !!x.
5.8.
, JavaScript ,
.
32 ,
.
, ,
.
.
32 ,
32 ,
32. ,
0 31. 32
5,
.
,
, ,
.
JavaScript.
:
(&)
&
. 1, 1
. 0x1234 & 0x00FF
0x0034.
(|)
|
. 1, 1
. , 9 | 10 11.
(^)
^
. ,
, , .
, (
) . , 9 ^ 10 3.
92
5.
(~)
~ ,
.
. JavaScript
~ 1.
, ~0x0f 0xfffffff0, 16.
(<<)
<<
, ,
0 31. , a << 1 a
, . .
, 32 .
2, 4,
. . , 7 << 1 14.
(>>)
>>
, ( 0 31). ,
, . (32) ,
. ,
;
, .
2 (
), 4 . .
, 7 >> 1 3, 7 >> 1 4.
(>>>)
>>> >> ,
. , 1 >> 4 1, 1 >>> 4 268435455 (0x0fffffff).
5.9.
4,
JavaScript =. :
i = 0
JavaScript ,
, =
.
= ,
. .
.
=
, , ,
,
.
93
5.9.
= ,
. ,
:
(a = b) == 0
, = == !
,
. ,
, :
i = j = k = 0;
, ,
. (
) (),
( ) .
5.9.1.
(=) JavaScript
,
. , += .
:
total += sales_tax
total = total + sales_tax
, += , .
, ,
.
=, *=, &= .
. 5.2.
5.2.
+=
a += b
a = a + b
=
a = b
a = a b
*=
a *= b
a = a * b
/=
a /= b
a = a / b
%=
a %= b
a = a % b
<<=
a <<= b
a = a << b
>>=
a >>= b
a = a >> b
>>>=
a >>>= b
a = a >>> b
&=
a &= b
a = a & b
|=
a |= b
a = a | b
^=
a ^= b
a = a ^ b
94
5.
( op
):
a op= b
a = a op b
, a ,
, .
5.10.
JavaScript ,
.
5.10.1. (?:)
(
) JavaScript .
?:,
. , ?, ? :,
:. :
x > 0 ? x*y : x*y
(
)
. .
, ,
. true,
. false,
.
if, ?:
. ,
, , , , ,
:
greeting = "hello " + (username != null ? username : "there");
if, :
greeting = "hello ";
if (username != null)
greeting += username;
else
greeting += "there";
5.10.2. typeof
typeof ,
. ,
.
typeof "number", "string" "boolean",
, .
5.10.
95
, ( ) null
"object". "function",
"undefined".
typeof "object",
Number, String Boolean. "object"
Date RegExp. , JavaScript,
, JavaScript,
typeof .
JavaScript typeof "object"
, .
typeof , , :
typeof i
(typeof value == "string") ? "'" + value + "'" : value
typeof , ty
peof , :
typeof(i)
typeof
"object", ,
.
, ,
instanceof constructor (
Object.constructor, ).
typeof ECMAScript v1 Java
Script 1.1 .
5.10.3. (new)
new
. ,
:
new ()
,
, ,
.
new JavaScript ,
, .
new:
o = new Object;
//
d = new Date();
// Date,
c = new Rectangle(3.0, 4.0, 1.5, 2.75); // Rectangle
obj[i] = new constructors[i]();
new ,
,
,
this.
96
5.
. 7 new,
this .
new
new Array().
7.
5.10.4. delete
delete ,
, .1 true,
, false .
JavaScript . ,
,
var. delete
, true. ( , ECMAScript ,
delete true, ,
.)
:
var o = {x:1, y:2}; // ;
delete o.x;
// ; true
typeof o.x;
// ; "undefined"
delete o.x;
// ; true
delete o;
// ; false
delete 1;
// ; true
x = 1;
// var
delete x;
// ; true
x;
// : x
: ,
undefined. ,
. 4.3.2.
, delete ,
, . :
var my = new Object();
my.hire = new Date();
my.fire = my.hire;
delete my.hire;
document.write(my.fire);
//
//
//
//
//
"my"
my.hire Date
my.fire
hire ; true
my.fire Date
5.10.5. void
void ,
. :
1
, C++, , delete
JavaScript delete C++. JavaScript
. delete C++,
, .
5.10.
97
undefined.
URL javascript:,
,
.
, void HTML:
<a href="javascript:void window.open();"> </a>
void undefined.
void ECMAScript v1 JavaScript 1.1. ECMA
Script v3 undefined, Java
Script 1.5.
void 0, undefined.
5.10.6.
(,) . ,
, . .
i=0, j=1, k=2;
2 :
i = 0;
j = 1;
k = 2;
;
,
, .
for,
6.
5.10.7.
3,
([]), (.).
, JavaScript .
,
( ).
, ;
. :
document.lastModified
navigator.appName
frames[0].length
document.write("hello world")
, JavaScript
, undefined.
, .
98
5.
:
. .
[] .
,
. ( )
, ( )
, . :
frames[1]
document.forms[i + j]
document.forms[i].elements[j++]
[] ,
, ,
. :
, .
, , ,
. :
document["lastModified"]
frames[0]['length']
data["val" + i]
[] .
, , . .
.
, ,
[].
for/in,
6. ,
o for/in []:
for (f in o) {
document.write('o.' + f + ' = ' + o[f]);
document.write('<br>');
}
5.10.8.
() JavaScript .
, .
,
.
, ,
. . ()
,
, . :
document.close()
Math.sin(x)
alert("Welcome " + name)
Date.UTC(2000, 11, 31, 23, 59, 59)
funcs[i].f(funcs[i].args[0], funcs[i].args[1])
, Java
Script, .
,
. , '
JavaScript,
.
JavaScript. JavaScript
, ,
.
JavaScript, ,
2.4 , JavaScript
. ,
JavaScript .
.
6.1.
JavaScript ,
. 5.
. :
s = " " + name;
i *= 3;
, ++ ,
. ,
:
counter++;
delete .
,
:
100
6.
delete o.x;
.
:
alert(" , " + name);
window.close();
,
, .
,
, . ,
:
Math.cos(x);
,
:
cx = Math.cos(x);
:
.
6.2.
5 ,
. JavaScript
.
.
,
, JavaScript
:
{
x = Math.PI;
cx = Math.cos(x);
alert("cos(" + x + ") = " + cx);
}
, ,
.
, .
, .
, JavaScript
(
); .
JavaScript ,
.
, .
, JavaScript
,
6.3. if
101
. ,
.
, break, continue, re
turn throw
.
.
6.3. if
if ,
JavaScript , ,
. . :
if ()
if .
true true,
. false false,
. :
if (username == null)
// username null undefined,
username = "John Doe"; //
:
// username null, undefined, 0, "" NaN,
// false, .
if (!username) username = "John Doe";
,
if.
,
. if :
if ((address == null) || (address == "")) {
address = "undefined";
alert(", .");
}
, , .
JavaScript,
,
.
, , .
if else,
, false. :
if ()
1
else
2
, true,
1, 2. :
102
6.
if (username != null)
alert(" " + username + "\n .");
else {
username = prompt(" !\n ?");
alert(" " + username);
}
if else
, else
if. :
i = j = 1;
k = 2;
if (i == j)
if (j == k)
document.write("i k");
else
document.write("i j"); // !!
if
if. , ( ,
), if else.
, JavaScript
:
if (i == j) {
if (j == k)
document.write("i k");
else
document.write("i j"); // OOPS!
}
JavaScript ( ):
else if.
, ,
, :
if (i == j) {
if (j == k) {
document.write("i k");
}
}
else { // !
document.write("i j");
}
if else (
, while) ,
.
, .
6.4. else if
, if/else
6.5. switch
103
. ?
else if.
JavaScript, ,
if/else:
if (n == 1) {
// 1
}
else if (n == 2) {
// 2
}
else if (n == 3) {
// 3
}
else {
// else , 4
}
.
if, if else
. else if
, :
if (n == 1) {
// 1
}
else {
if (n == 2) {
// 2
}
else {
if (n == 3) {
// 3
}
else {
// else , 4
}
}
}
6.5. switch
if .
if,
. ,
.
if.
switch
, if. switch JavaScript
switch Java C. switch
, if:
104
6.
switch() {
switch , .
case,
. switch,
, case,
. , ,
, case. case
, ,
default:. default: , .
switch ,
. switch
if/else, :
switch(n) {
case 1:
// , n == 1
// 1.
break; //
case 2:
// , n == 2
// 2.
break; //
case 3:
// , n == 3
// 3.
break; //
default: // ...
// 4.
break; //
}
break case.
break, ,
switch . case switch
,
. break switch
case, ,
, .
, case
, 99 % case
break. ( switch
break return.
switch case.)
switch;
, :
function convert(x) {
switch(typeof x) {
case 'number': //
return x.toString(16);
case 'string': // ,
return '"' + x + '"';
case 'boolean': // TRUE FALSE,
6.6. while
105
return x.toString().toUpperCase();
default:
//
return x.toString()
}
}
: case
. switch
, ECMAScript v3
case .1 :
case
case
case
case
60*60*24:
Math.PI:
n+1:
a[0]:
switch switch,
case , ,
.2
===, ==,
.
: case,
, ,
, . . switch
case.
, .
case .
, case
switch, switch
default:. default: , switch
. , default:
switch case.
,
switch.
6.6. while
if ,
JavaScript , while
1
106
6.
, JavaScript
. :
while ()
while .
false, JavaScript
, true, , ,
. , false, Java
Script ,
. ,
false, while JavaScript
. while(true) .
, JavaScript
.
.
, , ,
. , (
) ,
. , . . ,
true, !
while:
var count = 0;
while (count < 10) {
document.write(count + "<br>");
count++;
}
, count 0,
, .
10 , false
(. . count 10), while Java
Script .
, count.
i, j k,
, .
6.7. do/while
do/while while, ,
, . ,
. :
do
while ();
do/while , while. ,
,
, . :
6.8. for
107
function printArray(a) {
if (a.length == 0)
document.write(" ");
else {
var i = 0;
do {
document.write(a[i] + "<br>");
} while (++i < a.length);
}
}
do/while while . ,
do do ( ),
while ( ). ,
while, do . ,
do , ,
.
6.8. for
, for, ,
while. for , (
while).
.
,
. ,
,
.
, ,
; for
. ,
for, ,
. for:
for(; ; )
for,
while:1
;
while() {
;
}
,
. , ,
( ), . . .
1
continue, while
for.
108
6.
JavaScript ,
var,
.
, .
true, , .
. ,
, .
, , ++ .
while , 0 9,
for:
for(var count = 0; count < 10; count++)
document.write(count + "<br>");
,
, . ,
for
;
.
, ,
,
. JavaScript,
,
for. :
for(i = 0, j = 10; i < 10; i++, j)
sum += i * j;
6.9. for/in
for JavaScript .
for. for/in.
, :
for ( in )
, var,
, ,
(. . ,
). ,
. ,
, .
while for. for/in
. for/in
.
.
6.10.
109
[]. , for/in
:
for (var prop in my_object) {
document.write(": " + prop + "; : " + my_object[prop], "<br>");
}
: for/in ,
,
. , . .
. ,
:
var o = {x:1, y:2, z:3};
var a = new Array();
var i = 0;
for(a[i++] in o) /* */;
JavaScript . ,
for/in ,
. ,
0, 1 2 :
for(i in a) alert(i);
for/in ,
. , ,
JavaScript .
for/in , ,
. ,
, .
for/in .
( ), .
for/in. ,
, , ,
, . 7,
. ,
, for/in.
6.10.
case default: switch
.
:
:
JavaScript
, .
,
, .
while :
110
6.
parser:
while(token != null) {
//
}
, ,
. ,
while, do/while, for for/in. ,
break continue
.
6.11. break
break
switch. :
break;
break switch,
break .
JavaScript break:
break: _;
: _ ;
, .
break ,
;
, break.
switch; break,
,
switch. , break,
break .
, , if ,
.
2, break
. , JavaScript
.
break ,
, ,
.
break,
switch.
,
. ,
break, .
. ,
6.12. continue
111
; ,
break:
for(i = 0; i < a.length; i++) {
if (a[i] == target)
break;
}
break
switch ,
.
for break
. , ,
:
outerloop:
for(var i = 0; i < 10; i++) {
innerloop:
for(var j = 0; j < 10; j++) {
if (j > 3) break; //
if (i == 2) break innerloop; //
if (i == 4) break outerloop; //
document.write("i = " + i + " j = " + j + "<br>");
}
}
document.write("FINAL i = " + i + " j = " + j + "<br>");
6.12. continue
continue break.
continue . continue
, break:
continue;
continue :
continue _;
continue ,
while, do/while, for for/in.
.
continue,
. :
while ,
true, .
do/while ,
.
for
, ,
.
112
6.
for/in
.
continue while
for while , for
, .
for for
while. continue
, for while
.
continue
:
for(i = 0; i < data.length; i++) {
if (data[i] == null)
continue; //
total += data[i];
}
continue, break,
, ,
, continue. ,
break, continue
.
6.13. var
var .
:
var _1 [ = _1] [ ,..., _n [= _n]]
var
;
, . :
var
var
var
var
var
i;
j = 0;
p, q;
greeting = "hello" + name;
x = 2.34, y = Math.cos(0.75), r, theta;
var
, ,
, .
, var,
delete. : var
with (. 6.18) .
var ,
, (unde
fined).
6.14. function
113
JavaScript
4.
6.14. function
function JavaScript .
:
function _([1 [,2 [..., n]]]) {
_ .
, .
, .
, .
JavaScript,
.
.
(). ,
function.
while ,
, .
_.
:
function welcome() { alert(" !"); }
function print(msg) {
document.write(msg, "<br>");
}
function hypotenuse(x, y) {
return Math.sqrt(x*x + y*y); // return
}
function factorial(n) { //
if (n <= 1) return 1;
return n * factorial(n 1);
}
JavaScript .
,
, . .
if, while .
114
6.
function .
JavaScript,
.
,
JavaScript, . . .
JavaScript ,
( ) .
( ,
; ) ,
.
, ,
, .
:
alert(f(4));
//
//
var f = 0;
//
function f(x) { //
return x*x; //
}
alert(f);
//
16. f() ,
.
f.
"" f ,
.
0. f() f.
,
, . ,
.
8 .
6.15. return
, ()
. , return
, .
. return :
return ;
return .
.
return,
. return ,
. return
:
function square(x) { return x*x; }
return ,
, . :
function display_object(obj) {
//
//
if (obj == null) return;
6.16. throw
115
// ...
}
return
,
(undefined).
JavaScript ,
return .
6.16. throw
,
. (throw)
. '
(catch), , , . . ,
. Java
Script ,
,
throw. try/catch/finally,
.1
throw :
throw ;
.
Error Error.
,
, . ,
throw :
function factorial(x) {
// ,
// !
if (x < 0) throw new Error("x ");
//
for(var f = 1; x > 1; f *= x, x) /* */ ;
return f;
}
, JavaScript
2
. catch
try/catch/finally,
. , ,
catch,
1
116
6.
, .
, .
, try/catch/finally,
, , .
JavaScript
. ,
.
throw ECMAScript v3 Java
Script 1.4. Error ECMA
Script v3, JavaScript 1.5.
6.17. try/catch/finally
try/catch/finally Java
Script. try ,
. try catch
, , try
. catch finally, ,
,
try. catch, finally ,
try . try,
catch finally .
,
. throw, try/
catch/finally ECMAScript v3 JavaScript 1.4.
try/catch/fi
nally. , , , catch
.
. ,
catch. JavaScript
, :
try {
// .
//
// throw,
// , .
}
catch (e) {
// ,
// try .
// e, Error
// , throw.
// ,
// , ,
// throw.
}
finally {
// , , ,
// try. , try :
6.17. try/catch/finally
//
//
//
//
//
1)
2)
3)
4)
117
,
break, continue return
, catch
,
try/catch.
factorial(), ,
prompt() alert() JavaScript :
try {
//
var n = prompt(" ", "");
// , ,
var f = factorial(n);
//
alert(n + "! = " + f);
}
catch (ex) { // ,
//
alert(ex);
}
118
6.
return. , try/finally,
,
, continue:
var i = 0, total = 0;
while(i < a.length) {
try {
if ((typeof a[i] != "number") || isNaN(a[i])) // ,
continue; // .
total += a[i]; // .
}
finally {
i++;
// i, continue.
}
}
6.18. with
4
,
. with
. :
with ()
,
, .
with
. JavaScript
. , HTML
, , :
frames[1].document.forms[0].address.value
,
with :
with(frames[1].document.forms[0]) {
// , :
name.value = "";
address.value = "";
email.value = "";
}
frames[1].document.forms[0] .
, JavaScript
, address.
,
. JavaScript with
, ,
6.19.
119
. ,
with
.1 with .
. ,
:
var form = frames[1].document.forms[0];
form.name.value = "";
form.address.value = "";
form.email.value = "";
6.19.
, JavaScript
. :
;
, ,
. ,
, ,
, . :
// a
for(i=0; i < a.length; a[i++] = 0);
,
for while if
, . ,
, :
if ((a == 0) || (b == 0)); // ! ...
o = null;
// .
,
. :
for(i=0; i < a.length; a[i++] = 0) /* */ ;
6.20. JavaScript
JavaScript. . 6.1
.
, .
120
6.
6.1. JavaScript'
break
break;
break _;
switch
_
case
case :
switch
continue
continue;
continue _;
,
_
default
default:
switch
do/while
do
while
while ();
for
for (; ; )
for/in
for ( in )
function
if/else
if ()
1
[else 2]
return
return [];
,
switch
switch () {
,
case de
fault
throw
throw ;
121
6.20. JavaScript*
try
try {
}
catch () {
}
finally {
var
var _1 [ = _1]
[ ..., _n [ = _n]];
while
while ()
with
with ()
(
)
3 ,
JavaScript.
, , ,
, .
, ,
.
JavaScript.
7.1.
,
.
, ,
. ,
, ,
, .
.
( ), .
JavaScript ,
JavaScript.
:
var
var
var
var
empty = {}; //
point = { x:0, y:0 };
circle = { x:point.x, y:point.y+1, radius:2 };
homer = {
"name": "Homer Simpson",
"age": 34,
"married": true,
"occupation": "plant operator",
7.2.
123
'email': "homer@example.com"
};
,
, .
,
, ,
.
new .
,
. :
var a = new Array( ); //
var d = new Date( ); //
var r = new RegExp("javascript", "i"); //
7.2.
. (
). ,
. ,
, JavaScript
, .
. ,
. , p o
o.p, radius circle circle.radius.
:
. :
// . .
var book = new Object();
// .
book.title = "JavaScript: "
// . .
book.chapter1 = new Object();
book.chapter1.title = " JavaScript";
book.chapter1.pages = 11;
book.chapter2 = { title: " ", pages: 6 };
// .
alert(": " + book.title + "\n\t" +
124
7.
" 1 " + book.chapter1.title + "\n\t" +
" 2 " + book.chapter2.title);
, .
var,
( ) .
( )
:
book.title = "JavaScript: "
7.2.1.
for/in, 6, ,
, , .
,
.
, :
function DisplayPropertyNames(obj) {
var names = "";
for(var name in obj) names += name + "\n";
alert(names);
}
, for/in
, ,
, .
7.2.2.
in (. 5).
, . :
// o "x",
if ("x" in o) o.x = 1;
in ,
undefined.
, :
// x
// undefined, .
if (o.x !== undefined) o.x = 1;
: , ,
. , :
o.x = undefined
x , .
x 1,
.
7.3.
125
, , !=
!==. !== === undefined null,
:
// doSomething null
// undefined, , !
if (o.doSomething) o.doSomething();
7.2.3.
delete:
delete book.chapter2;
,
undefined; delete
. for/in : ,
undefined, .
7.3.
,
.
[], . ,
JavaScript :
object.property
object["property"]
,
, ,
, . , .
Java, C, C++
,
. JavaScript ,
;
.
.
JavaScript
.
[] . JavaScript ,
.
JavaScript , , :
var addr = "";
for(i = 0; i < 4; i++) {
addr += customer["address" + i] + '\n';
}
address0, add
ress1, address2 address3 customer.
126
7.
.
, ,
. , ,
.
,
.
portfolio, .
,
. , , , 50 IBM,
portfolio.ibm 50.
,
, .
, :
var stock_name = get_stock_name_from_user();
var shares = get_number_of_shares();
portfolio[stock_name] = shares;
, .
, portfolio
. [],
. . (
), (
).
,
,
.
(map): JavaScript (
) .
(.)
C++ Java, .
. JavaScript
Perl, C++ Java.
6 for/in. JavaScript
.
,
:
var value = 0;
for (stock in portfolio) {
//
// .
value += get_share_value(stock) * portfolio[stock];
}
7.4. Object
127
for/in,
.
(JavaScript) portfolio.
7.4.
Object
, JavaScript
Object. , , ,
, Date() RegExp(),
,
,
Object.
.
7.4.1. constructor
JavaScript constructor,
, . ,
d Date(), d.constructor
Date:
var d = new Date( );
d.constructor == Date; // true
, , ,
constructor
. , :
if ((typeof o == "object") && (o.constructor == Date))
// Date...
constructor instan
ceof, . . :
if ((typeof o == "object") && (o instanceof Date))
// Date...
7.4.2. toString()
toString() ; ,
/ , .
JavaScript ,
. , ,
+ ,
, alert() document.write().
toString() . ,
s "[object Object]":
var s = { x:1, y:1 }.toString( );
,
toString(). ,
128
7.
, ,
,
, .
9 , toString()
.
7.4.3. toLocaleString()
ECMAScript v3 JavaScript 1.5 Object toString()
toLocaleString().
. toLo
caleString(), Object, ;
, toString().
toLocaleString(). ECMA
Script v3 Array, Date Number toLocaleString(),
.
7.4.4. valueOf()
valueOf() toString(), ,
JavaScript
, , . Java
Script ,
. valueOf()
, ,
valueOf() (, Date.valueOf()). 9
, valueOf() .
7.4.5. hasOwnProperty()
hasOwnProperty() true,
,
. false. :
var o = {};
o.hasOwnProperty("undef");
// false:
o.hasOwnProperty("toString"); // false: toString
Math.hasOwnProperty("cos"); // true: Math cos
9.
hasOwnProperty() ECMAScript v3
JavaScript 1.5 .
7.4.6. propertyIsEnumerable()
propertyIsEnumerable() true,
, ,
for/in.
false. :
var o = { x:1 };
129
7.5.
o.propertyIsEnumerable("x");
// true:
o.propertyIsEnumerable("y");
// false:
o.propertyIsEnumerable("valueOf"); // false:
propertyIsEnumerable() ECMAScript v3
JavaScript 1.5 .
: , ,
.
( 9),
, hasOwnProperty().
7.4.7. isPrototypeOf()
isPrototypeOf() true, ,
, , .
false. :
var o = {};
Object.prototype.isPrototypeOf(o);
Object.isPrototypeOf(o);
o.isPrototypeOf(Object.prototype);
Function.prototype.isPrototypeOf(Object);
//
//
//
//
7.5.
, () .
, ,
, . JavaScript
, ,
.
, .
. JavaScript
. ,
, : ,
. ,
typeof "object".
,
. :
var empty = [];
//
var primes = [2, 3, 5, 7, 11]; //
var misc = [ 1.1, true, "a" ]; // 3
:
var base = 1024;
var table = [base, base+1, base+2, base+3];
130
7.
:
var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]];
0, 1, . .
,
:
var count = [1,,3]; // 3 , .
var undefs = [,,]; // 2 , .
Array().
:
:
var a = new Array( );
, [].
n :
var a = new Array(5, 4, 3, 2, 1, "testing, testing");
.
.
0. length
, .
, :
var a = new Array(10);
(
undefined) length
.
Array() ,
.
.
7.6.
[].
.
, .
, .
, JavaScript :
value = a[0];
a[1] = 3.14;
i = 2;
a[i] = 3;
a[i + 1] = "hello";
a[a[i]] = a[0];
7.6.
131
1. Java
Script ( C, C++ Java) 0.
, []
:
my['salary'] *= 2;
,
. () [].
, ,
2321. ,
( , ), JavaScript
,
. ,
"1.23", :
a[1.23] = true;
7.6.1.
, C Java, ,
. JavaScript
JavaScript ,
.
, :
a[10] = 10;
JavaScript . ,
;
JavaScript ,
.
JavaScript
0 10 000, 9 999 ,
:
a[0] = 1;
a[10000] = " 10,000";
: :
var c = new Circle(1,2,3);
c[0] = " !"
"0".
.
7.6.2.
delete undefined,
. ,
,
. Array.shift()
132
7.
, Array.pop() , Array.splice()
.
, .
7.6.3.
, Array(),
, length,
.
, : length
, .
, length
, .
:
var a = new Array();
a = new Array(10);
a = new Array(1,2,3);
a = [4, 5];
a[5] = 1;
a[49] = 0;
//
//
//
//
//
//
a.length
a.length
a.length
a.length
a.length
a.length
==
==
==
==
==
==
0 ( )
10 ( 09)
3 ( 02)
2 ( 0 1)
6 ( 0, 1 5)
50 ( 0, 1, 5 49)
, 2321, . .
length 2321.
7.6.4.
length
:
var fruits = ["", "", "", ""];
for(var i = 0; i < fruits.length; i++)
alert(fruits[i]);
, ,
0. ,
, :
for(var i = 0; i < fruits.length; i++)
if (fruits[i] != undefined) alert(fruits[i]);
, Array():
var lookup_table = new Array(1024);
for(var i = 0; i < lookup_table.length; i++)
lookup_table[i] = i * 512;
7.6.5.
length , .
length , ,
; , ,
, .
7.7.
133
length , ,
,
.
: ,
length.
, . ,
, ,
Array 7.7.
7.6.6.
JavaScript ,
.
[] .
, , matrix .
matrix[x] .
matrix[x][y]. ,
:
//
var table = new Array(10);
// 10
for(var i = 0; i < table.length; i++)
table[i] = new Array(10);
// 10
//
for(var row = 0; row < table.length; row++) {
for(col = 0; col < table[row].length; col++) {
table[row][col] = row*col;
}
}
// 5*7
var product = table[5][7];
// 35
7.7.
[]
, Array.
. Perl;
, Perl, .
, ,
.
7.7.1. join()
Array.join() .
,
. ,
. , "1,2,3":
var a = [1, 2, 3]; //
var s = a.join(); // s == "1,2,3"
134
7.
,
:
s = a.join(", "); // s == "1, 2, 3"
.
Array.join() String.split(),
.
7.7.2. reverse()
Array.reverse()
.
, ,
, .
, , reverse() join(),
"3,2,1":
var a = new Array(1,2,3);
a.reverse();
var s = a.join();
7.7.3. sort()
Array.sort()
. sort() ,
(
):
var a = new Array("banana", "cherry", "apple");
a.sort();
var s = a.join(", ");
// s == "apple, banana, cherry"
.
, ,
sort() .
,
. ,
.
,
, . (. .
), 0. , ,
, ,
:
var a = [33, 4, 1111, 222];
a.sort();
a.sort(function(a,b) {
return ab;
});
//
//
//
//
,
. ,
.
135
7.7.
,
,
( toLowerCase()).
,
: , . .
, , ,
, , .
7.7.4. concat()
Array.concat() ,
, concat(),
, concat().
,
. ,
. :
var a = [1,2,3];
a.concat(4, 5)
a.concat([4,5]);
a.concat([4,5],[6,7])
a.concat(4, [5,[6,7]])
//
//
//
//
[1,2,3,4,5]
[1,2,3,4,5]
[1,2,3,4,5,6,7]
[1,2,3,4,5,[6,7]]
7.7.5. slice()
Array.slice() , , .
.
,
, , ( )
, .
,
. ,
. , , 1,
, , 3,
. :
var a = [1,2,3,4,5];
a.slice(0,3);
//
a.slice(3);
//
a.slice(1,1);
//
a.slice(3,2);
//
[1,2,3]
[4,5]
[2,3,4]
[3]
7.7.6. splice()
Array.splice()
. , ,
slice() concat(). : splice() slice()
, .
splice() ,
.
136
7.
,
. splice()
, / .
, () .
,
. splice() (
) . :
var a = [1,2,3,4,5,6,7,8];
a.splice(4);
// [5,6,7,8]; a [1,2,3,4]
a.splice(1,2);
// [2,3]; a [1,4]
a.splice(1,1);
// [4]; a [1]
splice() ,
.
, , ,
, . :
var a = [1,2,3,4,5];
a.splice(2,0,'a','b');
a.splice(2,2,[1,2],3);
// []; a [1,2,'a','b',3,4,5]
// ['a','b']; a [1,2,[1,2],3,3,4,5]
, , concat(), splice()
.
, , .
//
//
//
//
//
//
//
//
:
:
:
:
:
:
:
:
[]
[1,2]
[1]
[1,3]
[1]
[1,[4,5]]
[1]
[]
2
2
2
3
2
[4,5]
1
137
7.7.
,
. :
var a = [];
a.unshift(1);
a.unshift(22);
a.shift();
a.unshift(3,[4,5]);
a.shift();
a.shift();
a.shift();
//
//
//
//
//
//
//
//
a:[]
a:[1]
a:[22,1]
a:[1]
a:[3,[4,5],1]
a:[[4,5],1]
a:[1]
a:[]
:
:
:
:
:
:
:
1
2
22
3
3
[4,5]
1
unshift()
. , (
splice()). ,
, .
, .
// '1,2,3'
// 'a,b,c'
// '1,2,c'
: toString() , join()
.
toLocaleString() toString().
toLocaleString() ,
( ) .
7.7.10.
Firefox Mozilla 1.5 JavaScript 1.6,
,
(array extras).
indexOf() lastIndexOf(),
( String.indexOf()
). ,
: forEach()
; map() ,
; filter()
, true.
Firefox
138
7.
, . .
Firefox
,
, http://developer.mozilla.org.
7.8. ,
JavaScript , length
:
.
.
JavaScript Array (instanceof Array),
.
JavaScript,
, .
, length
. ,
, .
length,
,
. ,
, .
length,
, , .
, , ,
.
var a = {}; //
// ,
var i = 0;
while(i < 10) {
a[i] = i * i;
i++;
}
a.length = i;
//
var total
for(var j
total
,
= 0;
= 0; j < a.length; j++)
+= a[j];
Argument, 8.2.2, ,
. JavaScript
(DOM), document.getEle
mentsByTagName().
JavaScript,
. '
, , ,
.
,
. ,
, . ,
, ,
.
Java
Script. , JavaScript
, eval() parseInt() sort()
Array. JavaScript ,
document.write() alert(). JavaScript
, , . ,
, .
JavaScript .
9.
8.1.
6,
function. function,
:
,
;
JavaScript, ,
.
140
8.
8.1 .
, .
:
, return.
return 6;
( )
; unde
fined. return,
(undefined).
8.1. JavaScript'
// , document.write().
// return, .
function print(msg)
{
document.write(msg, "<br>");
}
// , .
function distance(x1, y1, x2, y2)
{
var dx = x2 x1;
var dy = y2 y1;
return Math.sqrt(dx*dx + dy*dy);
}
// ( ), .
// , x! x , .
function factorial(x)
{
if (x <= 1)
return 1;
return x * factorial(x1);
}
,
(), 5. ,
, ( )
(
JavaScript,
). , 8.1,
:
print(", " + name);
print(" !");
total_dist = distance(0,0,2,1) + distance(2,1,3,5);
print(" : " + factorial(5)/factorial(13));
, ,
.
,
, ,
. : ,
8.1.
141
;
( , 8.8).
JavaScript ,
, JavaScript ,
. ,
typeof. , JavaScript ,
.
, ,
. , un
defined. ,
, ,
, .
, ,
,
, .
: print() 8.1 return,
undefined,
. distance() facto
rial() ,
.
8.1.1.
JavaScript .
:
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
. , , ,
.1 :
func
tion. ( )
.
8.1.2.
JavaScript .
3, ,
.
function, ,
1
JavaScript
, . , Netscape Java
Script 1.5
if.
142
8.
, ,
.
function :
function f(x) { return x*x; }
// function
var f = function(x) { return x*x; }; //
,
,
, . :
var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x 1); };
f. fact,
. ,
, JavaScript 1.5
.
JavaScript,
, .
, .
, ,
, ,
:
f[0] = function(x) { return x*x; }; //
a.sort(function(a,b){return ab;}); // ;
var tensquared = (function(x) {return x*x;})(10); //
8.1.3.
Java
Script.
, .
.
( ,
) .
,
.
. ,
,
: like_this(), , ,
, : likeThis(). , ,
, ,
, .
. Prototype
JavaScript (http://prototype.conio.net),
$() (, )
document.getElementById(). ( 2
8.2.
143
, JavaScript
.)
8.2.
JavaScript
,
. ,
,
.
.
8.2.1.
,
, undefined.
,
.
, ( null). :
// a o a.
// a null, a
function copyPropertyNamesToArray(o, /* */ a) {
if (!a) a = []; //
// null, a
for(var property in o) a.push(property);
return a;
}
,
:
// o p
var a = copyPropertyNamesToArray(o); // o
//
copyPropertyNamesToArray(p,a);
// p
if
|| :
a = a || [];
5 , || ,
true true.
. a, a
null , a
. .
:
, . ,
,
.
undefined null.
144
8.
8.2.2. :
Arguments
arguments ; arguments
, ,
Arguments. Arguments (. 7.8),
,
. Arguments callee,
.
JavaScript
, .
Arguments ,
. , f,
, x. ,
x arguments[0].
arguments[1]. ,
, arguments length,
. f,
, arguments.length 2.
arguments .
, ,
, JavaScript :
function f(x, y, z)
{
// ,
if (arguments.length != 3) {
throw new Error(" f " + arguments.length +
", 3.");
}
// ...
}
arguments JavaScript:
,
. , ,
max(),
(
Math.max()):
function max(/*...*/)
{
var m = Number.NEGATIVE_INFINITY;
// ,
for(var i = 0; i < arguments.length; i++)
if (arguments[i] > m) m = arguments[i];
//
return m;
}
var largest = max(1, 10, 100, 2, 3, 1000, 4, 5, 10000, 6);
8.2.
145
,
, (variadic func'
tions, variable arity functions varargs functions).
C.
:
.
arguments[] ,
,
.
, arguments
Arguments. Arguments
length, .
, .
ECMAScript Arguments
. , ,
arguments.length, ECMAScript
, . (
length Array 7.6.3.)
Arguments .
, Arguments
, . ar
guments[]
.
, arguments[].
arguments[] , . :
function f(x) {
print(x);
//
arguments[0] = null; // , x
print(x);
// "null"
}
, ,
. arguments[0] x
,
.
, , arguments JavaScript
, .
, Arguments
. arguments
.
8.2.2.1. callee
Arguments callee,
.
, , .
, :
146
8.
function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x 1);
}
8.2.3.
,
.
, ,
. ,
. ,
,
. ,
:
// length from to.
// from_start from
// , to_start to.
// .
function arraycopy(/* array */ from, /* index */ from_start,
/* array */ to, /* index */ to_start,
/* integer */ length)
{
//
}
// ,
// , from_start
// to_start 0.
function easycopy(args) {
arraycopy(args.from,
args.from_start || 0, // ,
//
args.to,
args.to_start || 0,
args.length);
}
// easycopy():
var a = [1,2,3,4];
var b = new Array(4);
easycopy({from: a, to: b, length: 4});
8.2.4.
JavaScript ,
,
8.2.
147
.
,
,
arraycopy().
(op
tional).
, :
function max(/* ... */) { /* */ }
3, JavaScript
. , ,
,
, ,
.
, toString() (,
), .
.
arraycopy(), .
. ,
(, , ,
). , ,
.
,
.
, ,
, , ,
, :
// ( , ) a.
// , null
// undefined .
function sum(a) {
if ((a instanceof Array) || //
(a && typeof a == "object" && "length" in a)) { // ,
var total = 0;
for(var i = 0; i < a.length; i++) {
var element = a[i];
if (!element) continue; // null undefined
if (typeof element == "number") total += element;
else throw new Error("sum(): ");
}
return total;
}
else throw new Error("sum(): ");
}
sum()
,
.
, ,
, , null undefined.
148
8.
JavaScript ,
,
. flexsum(),
(, ,
). ,
, .
.
, ,
, :
function flexisum(a) {
var total = 0;
for(var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (!element) continue; // null undefined
// n
var n;
switch(typeof element) {
case "number":
n = element;
//
break;
case "object":
if (element instanceof Array) //
n = flexisum.apply(this, element);
else n = element.valueOf( ); // valueOf
break;
case "function":
n = element( );
//
break;
case "string":
n = parseFloat(element);
//
break;
case "boolean":
n = NaN; //
break;
}
// .
if (typeof n == "number" && !isNaN(n)) total += n;
//
else
throw new Error("sum(): " + element + " ");
}
return total;
}
8.3.
,
, .
JavaScript
. JavaScript
8.3.
149
, , ,
,
, . .1
, JavaScript
, :
function square(x) { return x*x; }
square.
, .
, , :
var a = square(4); // a 16
var b = square;
// b , square
var c = b(5);
// c 25
,
. :
var o = new Object;
o.square = function(x) { return x*x; }; //
y = o.square(16);
// y 256
,
:
var a = new Array(3);
a[0] = function(x) { return x*x; }
a[1] = 20;
a[2] = a[0](a[1]); // a[2] 400
,
() JavaScript!
8.2 , ,
. ,
.
, , ,
.
8.2.
//
function
function
function
function
add(x,y) { return x + y; }
subtract(x,y) { return x y; }
multiply(x,y) { return x * y; }
divide(x,y) { return x / y; }
//
//
1
,
, Java, ,
.
150
8.
, Array.sort().
. (,
, , , . .), sort()
,
, .
, , ,
, .
Array.sort()
! (
Array.sort() 7.7.3.)
8.4.
, ,
. ,
, , ,
. ,
8.4.
151
. , f o,
m:
o.m = f;
o m(), :
o.m();
, m() :
o.m(x, x+2);
: ,
, this .
o.m(),
o this.
:
var calculator = {
//
operand1: 1,
operand2: 1,
compute: function( ) {
this.result = this.operand1 + this.operand2;
}
};
calculator.compute();
// 1+1?
print(calculator.result); //
this . ,
,
, . ,
, ,
, .
:
rect.setSize(width, height);
setRectSize(rect, width, height);
, ,
rect (),
,
rect. (
, ,
.)
, , this
. ,
( ), ,
. this
( ).
: this ,
. JavaScript
this.
152
8.
8.5.
,
new.
9.
, new Function,
,
this.
8.6.
, JavaScript
. typeof "function",
JavaScript .
, ,
, RegExp Date.
8.6.1. length
, length arguments
, . length
.
, , . .
. ,
,
arguments, , . length
Function ,
. : arguments.length,
length , .
check(),
. arguments.length
Function.length ( arguments.callee.length)
, , .
, . check()
f(), check():
function check(args) {
var actual = args.length;
//
var expected = args.callee.length; //
if (actual != expected) {
// ,
throw new Error(" : : " +
expected + "; " + actual);
}
}
function f(x, y, z) {
// ,
// . ,
check(arguments);
//
8.6.
153
return x + y + z;
}
8.6.2. prototype
prototype,
'. , ,
new,
. proto
type 9.
8.6.3.
,
,
Function,
. , ,
.
. ,
,
.
, ,
Function, . .
. ,
:
// "" .
// ,
//
//
uniqueInteger.counter = 0;
// .
// ""
// .
function uniqueInteger() {
// ""
return uniqueInteger.counter++;
}
154
8.
o.m = f;
o.m(1,2);
delete o.m;
apply() call(), ,
:
f.apply(o, [1,2]);
, ,
apply() Math.max():
var biggest = Math.max.apply(null, array_of_numbers);
8.7.
, . 8.3
.
8.3.
// , "o"
function getPropertyNames(/* */o) {
var r = [];
for(name in o) r.push(name);
return r;
}
// "from" "to".
// "to" null, .
// "to" .
function copyProperties(/* */ from, /* */ to) {
if (!to) to = {};
for(p in from) to[p] = from[p];
return to;
}
// "from" "to",
// , "to".
// , , "from"
// , ,
// "to".
function copyUndefinedProperties(/* */ from, /* */ to) {
for(p in from) {
if (!p in to) to[p] = from[p];
}
}
8.4 .
8.4.
// "a" .
// , ,
8.7.
155
// true
function filterArray(/* */ a, /* */ predicate) {
var results = [];
var length = a.length; // , length!
for(var i = 0; i < length; i++) {
var element = a[i];
if (predicate(element)) results.push(element);
}
return results;
}
// ,
// "f"
function mapArray(/* */a, /* */ f) {
var r = [];
//
var length = a.length; // , f length!
for(var i = 0; i < length; i++) r[i] = f(a[i]);
return r;
}
, 8.5 .
.
, .
, ,
.
8.5.
// ,
// "f" "o". ,
// .
// , , ,
// , .
function bindMethod(/* */ o, /* */ f) {
return function() { return f.apply(o, arguments) }
}
// ,
// "f"
// , .
// ( "currying".)
function bindArguments(/* */ f /*, ... */) {
var boundArgs = arguments;
return function() {
// . ,
// , ,
var args = [];
for(var i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
for(var i = 0; i < arguments.length; i++) args.push(arguments[i]);
//
return f.apply(this, args);
}
}
156
8.
8.8.
4, JavaScript
, .
, , .1
8.8.1.
JavaScript ,
. , ,
, .
.
,
. ,
. ,
.
: ,
, ,
, . ,
,
.
8.8.2.
JavaScript ,
,
.
,
ECMAScript (activation object).
arguments, Argu
ments .
. ,
var, .
,
, Arguments
. ,
.
: this, arguments,
, .
8.8.3.
,
, ,
1
,
.
8.8.
157
,
. , ,
JavaScript,
JavaScript (,
JavaScript, ). , ,
, ,
. :
,
, ,
.
,
.
:
function init( ) {
// .
// ,
//
// .
}
init( ); // !
init, .
,
. ,
:
(function( ) { // .
// .
// ,
// .
})(); // .
,
, JavaScript.
8.8.4.
, JavaScript ,
,
. ,
g, f.
f, ,
. g f,
,
g. g,
: ,
f .
158
8.
,
, .
, :
var x = "";
function f( ) {
var x = "";
function g() { alert(x); }
g();
}
f(); // ""
JavaScript ,
, ,
. . ,
. ,
, .
. JavaScript
, ,
. (
.)
, ,
.
,
, ,
, :
//
// ,
//
function makefunc(x) {
return function() { return x; }
}
// makefunc() :
var a = [makefunc(0), makefunc(1), makefunc(2)];
// .
// ,
// , :
alert(a[0]( )); // 0
alert(a[1]( )); // 1
alert(a[2]( )); // 2
,
:
, .
,
. .
,
. ,
. ,
8.8.
159
.
, .
.
, ,
,
.
,
. ,
,
, ,
.
,
. ,
.
,
. ,
,
,
. JavaScript
,
,
. (,
,
, ,
, .)
JavaScript
, .
(closure). JavaScript
.
,
, .
, , .
.
, , .
,
JavaScript.
8.8.4.1.
,
. ,
.
,
. 8.6.3
uniqueInteger(), .
160
8.
(private)
. ,
:
//
uniqueID = function() {
if (!arguments.callee.id) arguments.callee.id = 0;
return arguments.callee.id++;
};
, uniqueID.id
0,
,
.
, :
uniqueID = (function() { //
var id = 0;
// ,
//
// ,
// .
// uniqueID .
return function() { return id++; }; //
})(); // .
8.6 . ,
, , ,
.
8.6.
// "o"
// . get<name>
// set<name>.
// ,
// .
// false, .
//
// ,
// , ,
// "o", .
// , ,
// .
// ,
// , .
function makeProperty(o, name, predicate) {
var value; // This is the property value
// .
o["get" + name] = function() { return value; };
// ,
// .
o["set" + name] = function(v) {
if (predicate && !predicate(v))
throw "set" + name + ": " + v;
8.8.
161
else
value = v;
};
}
// makeProperty().
var o = {}; //
// getName() setName()
//
makeProperty(o, "Name", function(x) { return typeof x == "string"; });
o.setName("Frank"); //
print(o.getName( )); //
o.setName(0);
//
, , ,
(Steve Yen) http://trimpath.com
TrimPath. ,
,
, ,
. , ,
(
)
eval() . eval()
JavaScript (
).
, ,
:
//
// eval( )
var inspector = function($) { return eval($); }
$,
.
, ,
8.7.
8.7.
// .
// ,
// .
// ,
// .
//
// breakpoint()
// http://trimpath.com/project/wiki/TrimBreakpoint
function inspect(inspector, title) {
var expression, result;
//
162
8.
// "ignore" .
if ("ignore" in arguments.callee) return;
while(true) {
// ,
var message = "";
// title,
if (title) message = title + "\n";
// ,
if (expression) message += "\n"+expression+" ==> "+result+"\n";
else expression = "";
// :
message += " , :";
// ,
// .
expression = prompt(message, expression);
//
//
//
if
( ),
.
(!expression) return;
//
// .
// .
result = inspector(expression);
}
}
:
inspect() 8.7 Window.prompt() (
).
,
:
function factorial(n) {
//
var inspector = function($) { return eval($); }
inspect(inspector, " factorial()");
var result = 1;
while(n > 1) {
result = result * n;
n;
inspect(inspector, "factorial( ) loop");
}
inspect(inspector, " factorial()");
return result;
}
8.9. Function()
163
.
, ,
.
, , JavaScript
, (,
), , , JavaScript.
.
,
,
, ,
.
, .
.
: http://msdn.microsoft.com/library/en'us/
IETechCol/dnwebgen/ie_leak_patterns.asp.
8.9. Function()
,
function ,
.
Function().
Function() ,
, .
:
var f = new Function("x", "y", "return x*y;");
, ,
:
function f(x, y) { return x*y; }
Function() .
. Java
Script, .
,
. ,
.
: Function() ,
. ,
Function(), .
, Function(),
:
Function()
.
eval() ( ).
164
8.
Function()
.
,
.
, ,
, ,
. (, , ,
, .)
:
Function(),
, ,
,
:
var y = "";
function constructFunction() {
var y = "";
return new Function("return y"); // !
}
// "", ,
// Function(), .
// ,
// "".
alert(constructFunction()()); // ""
,
JavaScript 7,
,
.
. ,
Complex,
, Complex
.
JavaScript ,
, Java, C++ C#.1 JavaScript
,
.
JavaScript.
,
, JavaScript 2.0
.
9.1.
7
{}, :
new Object()
,
:
1
JavaScript 2.0.
166
9. ,
new .
,
,
this. , new, '
, .
, ,
. ,
, ,
this.
, :
// .
// , "this".
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
// Rectangle.
// , .
var rect1 = new Rectangle(2, 4);
// rect1 = { width:2, height:4 };
var rect2 = new Rectangle(8.5, 11); // rect2 = { width:8.5, height:11 };
,
, this.
,
, Rectangle(),
width height.
, ,
Rectangle.
,
, ,
. , new Rectangle(1, 2),
, , new init_rect(1, 2).
,
, this.
,
new. ,
this, .
9.2.
8 , ,
. , ,
, this.
, ,
Rectangle. :
function computeAreaOfRectangle(r) { return r.width * r.height; }
9.2.
167
,
. ,
,
. :
// Rectangle
var r = new Rectangle(8.5, 11);
//
r.area = function() { return this.width * this.height; }
// ,
var a = r.area();
,
. ,
area .
Rectangle():
function Rectangle(w, h) {
this.width = w;
this.height = h;
this.area = function( ) { return this.width * this.height; }
}
:
// U.S. Letter
var r = new Rectangle(8.5, 11);
var a = r.area();
,
. .
width height
, area Rectangle
(,
, , , ,
).
,
, .
. , JavaScript
, .
,
. , , JavaScript '
.
, new
. .
new
. prototype
. prototype,
.
.
constructor ,
168
9. ,
. ( constructor
7, ,
constructor.) , ,
, .
.
Rectangle():
// ,
// .
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
// ,
// .
Rectangle.prototype.area = function() { return this.width * this.height; }
,
width height, .
, ,
, , . ,
.
,
.
; ,
. . ,
,
, . .
. , ,
.
( ).
.
for/in
in. Object.hasOwnProperty():
var r = new Rectangle(2, 3);
r.hasOwnProperty("width"); // true: width "r"
r.hasOwnProperty("area"); // false: area "r"
"area" in r;
// true: area "r"
9.2.1.
,
,
.
, JavaScript
.
p o, JavaScript , o
p. , ,
p . .
9.2.
169
, JavaScript
. , ,
: , o.p, o
p. , JavaScript
p o
. p
, , .
,
. p o,
,
p. , o
p, p .
p, JavaScript o.
p, o,
, JavaScript p.
, p () p .
,
. 9.1.
. 9.1.
170
9. ,
, ,
, ,
.
. (
)
.
,
. ,
,
, .
9.2.2.
, , .
, String Date, ,
. ,
, String:
// true, c
String.prototype.endsWith = function(c) {
return (c == this.charAt(this.length1))
}
endsWith() String,
:
var message = "hello world";
message.endsWith('h') // false
message.endsWith('d') // true
:
, , Java
Script. ,
, , ,
.
JavaScript,
, .
: Object.pro
totype.
for/in, Object.prototype,
JavaScript. {}, ,
. Object.prototype
, , ,
,
.
, ,
JavaScript. JavaScript ,
Java,
, ,
9.2.
171
. , ,
, .
,
,
JavaScript,
. , Function.apply() Microsoft Internet Exp
lorer 4 5 . ,
, :
// Function.apply() ,
// , (Aaron Boodman).
if (!Function.prototype.apply) {
//
// . eval()
Function.prototype.apply = function(object, parameters) {
var f = this;
//
var o = object || window;
// ,
var args = parameters || []; //
// o.
// ,
o._$_apply_$_ = f;
// eval().
// .
// .
var stringArgs = [];
for(var i = 0; i < args.length; i++)
stringArgs[i] = "args[" + i + "]";
// ,
// .
var arglist = stringArgs.join(",");
//
var methodcall = "o._$_apply_$_(" + arglist + ");";
// eval()
var result = eval(methodcall);
//
delete o._$_apply_$_;
//
return result;
};
}
,
Firefox 1.5 (. 7.7.10). Ar
ray.map() ,
, :
// Array.map() f
// , .
// map() , f
172
//
//
//
if
9. ,
. f() 3 .
, , .
.
(!Array.prototype.map) {
Array.prototype.map = function(f, thisObject) {
var results = [];
for(var len = this.length, i = 0; i < len; i++) {
results.push(f.call(thisObject, this[i], i, this));
}
return results;
}
9.3. JavaScript
JavaScript , ,
.
,
C++ Java.
.
JavaScript
. , , JavaScript
. JavaScript
.
( )
,
.
JavaScript ,
,
, Java C++.
. JavaScript
, Java C++.1
, . ,
, ,
,
.
, , , ,
. JavaScript ,
.
, Java C++, .
2, .
JavaScript
1
,
.
Java C++ ,
, JavaScript.
9.3. * JavaScript
173
, , ,
, .
Java C++ . ,
, .
. JavaScript ,
, ,
.
JavaScript, , ,
. ,
. ,
.
(. . ) .
Java
, .
.
Java
Script. , Rectangle
, rect.
Java :
, , .
, JavaScript .
9.3.1.
.
, 10 , 10
. , Rectangle Rectang
le width, .
width .
,
. , , r ,
Rectangle,
:
r.width
JavaScript
.
, , JavaScript
, /
.
9.3.2.
,
, , . ( Java
, JavaScript, Java
.)
174
9. ,
, . area() Rectangle
. Rectangle
:
a = r.area( );
, ,
, this.
, ,
, .
. Java
Script
. , ,
,
.
9.3.2.1. this
, Java C++,
JavaScript. Java C++
this. , , area Java
:
return width * height;
JavaScript this
:
return this.width * this.height;
this
, with ( 6.18),
:
Rectangle.prototype.area = function( ) {
with(this) {
return width*height;
}
}
9.3.3.
Java , ,
. ,
, . ,
,
. Number.MAX_VALUE
JavaScript, , MAX_VALUE
Number. ,
.
, ,
JavaScript,
. , JavaScript
9.3. * JavaScript
175
. ,
Rectangle.UNIT
1x1 :
Rectangle.UNIT = new Rectangle(1,1);
Rectangle , JavaScript
,
, .
9.3.4.
, , ;
, .
Date.parse() ( ) .
Date,
Date.
,
this
, this
. ( this .)
, .
, , ,
, .
, Java
Script .
JavaScript,
.
9.3.5. : Circle
9.1
, , .
, ,
.
9.1. Circle
// .
function Circle(radius) {
// r ,
// .
this.r = radius;
}
// Circle.PI , . . .
Circle.PI = 3.14159;
// , .
Circle.prototype.area = function( ) { return Circle.PI * this.r * this.r; }
// Circle .
Circle.max = function(a,b) {
176
9. ,
if (a.r > b.r) return a;
else return b;
}
//
var c = new Circle(1.0);
//
c.r = 2.2;
//
var a = c.area();
//
var x = Math.exp(Circle.PI); //
var d = new Circle(1.2);
//
var bigger = Circle.max(c,d); //
:
Circle
r
area()
PI
Circle
max()
9.3.6. :
9.2 Java
Script, , .
.
9.2.
/*
* Complex.js:
* Complex .
* ,
* , i 1.
*/
/*
*
* .
* . " ",
* .
*/
function Complex(real, imaginary) {
this.x = real;
//
this.y = imaginary; //
}
/*
*
* ( ) .
* , ,
* . ,
* this.
* .
*/
// .
// (0,0).
Complex.prototype.magnitude = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
};
// .
Complex.prototype.negative = function() {
9.3. * JavaScript
177
178
9. ,
9.3.7.
, C++,
(private) ,
.
, ,
/. JavaScript
( 8.8),
,
.
, .
Rectangle,
:
function ImmutableRectangle(w, h) {
// ,
// .
//
// .
this.getWidth = function() { return w; }
this.getHeight = function() { return h; }
}
// : .
ImmutableRectangle.prototype.area = function( ) {
return this.getWidth( ) * this.getHeight( );
};
(, ,
), , (Douglas Crockford).
http://www.crockford.com/
javascript/private.html.
9.4. Object
JavaScript ,
.
.
9.4.1. toString()
toString() ,
toString() .
, toString(),
.
, . .
.
, . ,
9.4. Object
179
parse()
, toString(), .
Complex 9.2 toString(),
toString()
Circle:
Circle.prototype.toString = function () {
return "[ " + this.r + " ("
+ this.x + ", " + this.y + ").]";
}
toString() Circle
:
" 1 (0, 0)."
9.4.2. valueOf()
valueOf() toString(), , Java
Script
, . ,
,
, this.
,
.
valueOf(), Object,
, , .
, Number Boolean,
, valueOf() ,
. Number Boolean
, .
,
.
valueOf(). 9.2, ,
valueOf() Complex.
.
Complex ,
. , , :
var
var
var
var
a
b
c
d
=
=
=
=
new Complex(5,4);
new Complex(2,1);
Complex.sum(a,b); // c {7,5}
a + b;
// d 7
valueOf() :
valueOf()
toString(). , valueOf() ,
,
, toString(). Complex:
alert("c = " + c);
// valueOf(); "c = 7"
alert("c = " + c.toString()); // "c = {7,5}"
180
9. ,
9.4.3.
JavaScript ,
. , , ,
, ,
.1
(, < >).
,
, .
Java
, JavaScript.
,
equals().
true, ,
. , ,
. ,
, . Complex
9.2 equals().
,
. ,
, . ,
Complex ,
magnitude(). Circle
X Y? ,
?
JavaScript ,
< <=, valueOf() ,
, .
Complex valueOf(),
, Complex
, .2
.
, ( ,
, Java)
compareTo().
compareTo()
, . this , ,
1
. '
. . .
, ,
. ,
valueOf() ( ,
)
, . . . .
181
9.4. Object
, compareTo()
. this , ,
, . ,
, .
,
:
a < b
a.compareTo(b) < 0
a <= b
a.compareTo(b) <= 0
a > b
a.compareTo(b) > 0
a >= b
a.compareTo(b) >= 0
a == b
a.compareTo(b) == 0
a != b
a.compareTo(b) != 0
compareTo() Complex
9.2, :
Complex.prototype.compareTo = function(that) {
//
// magnitude(), .
// 1 1,
// ,
// , .
if (!that || !that.magnitude || typeof that.magnitude != "function")
throw new Error(" Complex.compareTo()");
// ,
// , .
// compareTo().
return this.magnitude() that.magnitude();
}
,
, .
Array.sort()
,
, compareTo(). compareTo()
:
complexNumbers.sort(new function(a,b) { return a.compareTo(b); });
,
compare() ,
compareTo(). ,
, :
Complex.compare = function(a,b) { return a.compareTo(b); };
182
9. ,
:
complexNumbers.sort(Complex.compare);
: compare() compareTo()
Complex 9.2. ,
equals(), . equals()
, Complex ,
. compareTo()
, .
1+0i 0+1i
compareTo(), equals() ,
. , equals() compa
reTo() , .
. compareTo(),
equals():1
//
// . ,
Complex.prototype.compareTo = function(that) {
var result = this.x that.x; //
//
if (result == 0)
// ...
result = this.y that.y; //
// ,
// ,
return result;
};
9.5.
Java, C++
. ,
. ,
. . , . , JavaScript
.
JavaScript .
JavaScript Object ,
, .
, Object .
Object.
,
. Object? ,
;
1
< >. . . .
9.5.
183
Object(). , Ob
ject.prototype! Complex Com
plex.prototype, Object.prototype.
Complex,
. ,
Complex.prototype. ,
, Object.prototype.
: Complex
, Object, Complex.prototype
Object.prototype. , ,
9.2, Complex.prototype
toString(). Object.prototype ,
Complex , toString() Complex.proto
type .
, ,
Object. Java
Script;
. ,
. , Rectangle,
, .
,
Rectangle Rectang
le.prototype. 9.3 Rectanle
PositionedRectangle.
9.3. JavaScript
// .
//
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function( ) { return this.width * this.height; }
//
function PositionedRectangle(x, y, w, h) {
//
// width height .
// call,
// .
// .
Rectangle.call(this, w, h);
//
this.x = x;
this.y = y;
}
// ,
// PositionedRectangle(),
// Object.
184
9. ,
// Rectangle, .
PositionedRectangle.prototype = new Rectangle();
// ,
// width height,
// Rectangle, .
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;
//
// Rectangle(), constructor
// . , PositionedRectangle
// ,
// constructor
PositionedRectangle.prototype.constructor = PositionedRectangle;
//
// , .
PositionedRectangle.prototype.contains = function(x,y) {
return (x > this.x && x < this.x + this.width &&
y > this.y && y < this.y + this.height);
}
9.3, JavaScript
, Object.
,
.
.
, constructor
.1 ,
,
, .
PositionedRectangle,
:
var r = new PositionedRectangle(2,2,2,2);
print(r.contains(3,3)); //
print(r.area( ));
//
// :
print(r.x + ", " + r.y + ", " + r.width + ", " + r.height);
// 3
1
9.5.
185
9.5.1.
Positioned
Rectangle() .
. ,
superclass :
// .
PositionedRectangle.prototype.superclass = Rectangle;
,
. ,
, ,
superclass,
this.superclass (),
().
, ,
, 9.3.
,
:
function PositionedRectangle(x, y, w, h) {
this.superclass(w,h);
this.x = x;
this.y = y;
}
:
this. , call()
apply() .
9.5.2.
, ,
, (overrides) . ,
, .
, toString()
toString() Object.
,
, .
.
. ,
.
. , Rectangle
toString() ( )
:
186
9. ,
Rectangle.prototype.toString = function( ) {
return "[" + this.width + "," + this.height + "]";
}
toString() Rectangle,
PositionedRectangle,
,
, . PositionedRectangle
, toString()
.
, width height
. :
PositionedRectangle.prototype.toString = function() {
return "(" + this.x + "," + this.y + ") " + //
Rectangle.prototype.toString.apply(this); //
}
toString()
. :
apply(), ,
.
PositionedRectangle.prototype superclass,
, :
PositionedRectangle.prototype.toString = function( ) {
return "(" + this.x + "," + this.y + ") " + //
this.superclass.prototype.toString.apply(this);
}
, superclass
.
, .
9.6.
, . JavaScript
,
. JavaScript ,
( )
. 9.4 ,
.
9.4.
// .
// .
// , Object, Array, Date RegExp
// .
function borrowMethods(borrowFrom, addTo) {
var from = borrowFrom.prototype; //
187
9.6.
var to = addTo.prototype;
//
for(m in from) { //
if (typeof from[m] != "function") continue; // ,
//
to[m] = from[m];
//
}
}
, ,
.
.
9.5 ,
, ,
. ,
, ', .
9.5. ' ,
// .
// toString(), .
function GenericToString() {}
GenericToString.prototype.toString = function( ) {
var props = [];
for(var name in this) {
if (!this.hasOwnProperty(name)) continue;
var value = this[name];
var s = name + ":"
switch(typeof value) {
case 'function':
s += "function";
break;
case 'object':
if (value instanceof Array) s += "array"
else s += value.toString( );
break;
default:
s += String(value);
break;
}
props.push(s);
}
return "{" + props.join(", ") + "}";
}
// equals(), .
function GenericEquals() {}
GenericEquals.prototype.equals = function(that) {
if (this == that) return true;
//
//
//
//
, this ,
that,
: .
=== . ,
188
9. ,
// , ,
// , , equals() true
var propsInThat = 0;
for(var name in that) {
propsInThat++;
if (this[name] !== that[name]) return false;
}
// , this
var propsInThis = 0;
for(name in this) propsInThis++;
// this ,
// ,
if (propsInThis != propsInThat) return false;
// .
return true;
Rectangle, toString()
equals(), :
// Rectangle
function Rectangle(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function( ) { return this.width * this.height; }
//
borrowMethods(GenericEquals, Rectangle);
borrowMethods(GenericToString, Rectangle);
, , .
ColoredRec
tangle. Rectangle
Colored:
// , . ,
// , .
function Colored(c) { this.color = c; }
Colored.prototype.getColor = function() { return this.color; }
//
function ColoredRectangle(x, y, w, h, c) {
this.superclass(x, y, w, h); //
Colored.call(this, c);
// Colored
}
// Rectangle
ColoredRectangle.prototype = new Rectangle();
ColoredRectangle.prototype.constructor = ColoredRectangle;
ColoredRectangle.prototype.superclass = Rectangle;
9.7.
189
// Colored
borrowMethods(Colored, ColoredRectangle);
ColoredRectangle Rectangle ( ),
Colored. Rectangle Object
GenericEquals GenericToString.
,
. ColoredRectangle Colored,
ColoredRectangle
Colored. instanceof ,
9.7.3 ,
, .
9.7.
JavaScript , JavaScript
. JavaScript ,
.
,
typeof ( . 5.10.2). typeof
,
. , typeof null "ob
ject", typeof undefined "undefined".
"object",
,
"function", .
9.7.1. instanceof
, ,
, instanceof,
. , x ,
true:
x instanceof Array
instanceof ,
, . :
.
, o o instanceof Object
true. , instanceof , ,
true:
typeof f == "function"
f instanceof Function
f instanceof Object
,
,
constructor.
:
var d = new Date();
190
9. ,
9.7.2.
Object.toString()
instanceof constructor ,
,
, , , .
Object.toString().
7, Object
toString() . ,
, .
toString() ,
. ECMAScript ,
toString() :
[object class]
class ,
. , class "Array",
"Function", / "Date".
Math "Math", Error
"Error". JavaScript ,
JavaScript, class
, (, "Window", "Document" "Form").
, , Circle
Complex, , class
"Object". toString()
.
toString()
, , ,
. Ob
ject.prototype apply() ,
:
Object.prototype.toString.apply(o); // toString()
9.6 ,
. ,
toString() ,
classname
, .
9.6.
function getType(x) {
// x null, "null"
if (x == null) return "null";
// typeof
var t = typeof x;
9.7.
191
// ,
if (t != "object") return t;
// , x . toString()
// .
var c = Object.prototype.toString.apply(x); // "[object class]"
c = c.substring(8, c.length1);
// "[object" "]"
// Object, .
if (c != "Object") return c;
// "Object", , x
// .
if (x.constructor == Object) return c;
// "Object"
//
// classname,
if ("classname" in x.constructor.prototype &&
//
typeof x.constructor.prototype.classname == "string") //
return x.constructor.prototype.classname;
// , .
return "<unknown type>";
}
9.7.3.
: ,
, !. JavaScript ,
:
, , .
, JavaScript,
: X,
X,
X().1
,
.
Rectangle, equals() GenericEquals.
Rectangle
GenericEquals. instanceof ,
( 9.7).
9.7.
// true, c.prototype
// o. o , ,
// o .
// : ,
// , . ,
// , false.
function borrows(o, c) {
1
Ruby. .
192
9. ,
// o c, true
if (o instanceof c) return true;
//
//
//
//
//
//
if
, .
, ,
undefined, " ".
undefined false,
false, .
(c == Array || c == Boolean || c == Date || c == Error ||
c == Function || c == Number || c == RegExp || c == String)
return undefined;
borrows() 9.7 :
true, o , c.
:
o c, ,
c. JavaScript
()
. 9.8 , .
9.8.
// true, o
// , c.prototype.
// false. ,
// , .
function provides(o, c) {
// o c, "" c
if (o instanceof c) return true;
// ,
if (typeof o == "function") o = o.prototype;
//
//
//
if
,
undefined.
.
(c == Array || c == Boolean || c == Date || c == Error ||
c == Function || c == Number || c == RegExp || c == String)
return undefined;
9.7.
//
if
//
if
193
, , false
(typeof o[p] != "function") return false;
, false.
(o[p].length != proto[p].length) return false;
}
// , true.
return true;
}
provide()
compareTo(), 9.4.3. ,
compareTo() ,
,
compareTo(). Comparable:
function Comparable( ) {}
Comparable.prototype.compareTo = function(that) {
throw "Comparable.compareTo() . !";
}
Comparable :
, .
, :
// , o p
// compareTo()
if (o.constructor == p.constructor && provides(o, Comparable)) {
var order = o.compareTo(p);
}
: , , borrows()
provides(), undefined,
JavaScript, Array.
,
for/in.
undefined,
, ,
true.
Array . , 7.8
( ),
, ,
.
, ,
. 9.9.
9.9. ,
function isArrayLike(x) {
if (x instanceof Array) return true;
//
if (!("length" in x)) return false;
// length
if (typeof x.length != "number") return false; // length ,
if (x.length < 0) return false;
//
if (x.length > 0) {
// , length1
194
9. ,
if (!((x.length1) in x)) return false;
}
return true;
9.8. :
defineClass()
define
Class(), ,
, , .
9.10.
9.10.
/**
* defineClass() JavaScript.
*
* .
* JavaScript,
* , .
* , :
* , .
*
* , ,
* :
*
* name:
.
*
, classname .
*
* extend:
.
*
Object().
*
superclass .
*
* construct: .
*
. ,
*
constructor .
*
* methods: , ( ,
*
) .
*
.
*
.
*
"classname", "superclass" "constructor"
*
.
*
* statics: , (
*
) .
*
. .
*
* borrows: .
*
*
,
*
.
9.8. : defineClass()
195
*
,
*
, ,
*
, .
*
:
*
,
*
.
*
, ,
*
.
*
.
*
* provides: .
*
,
*
,
*
, .
*
, ,
*
"" ,
*
. ,
*
.
*
( )
*
. ,
*
.
**/
function defineClass(data) {
// .
// .
var classname = data.name;
var superclass = data.extend || Object;
var constructor = data.construct || function( ) {};
var methods = data.methods || {};
var statics = data.statics || {};
var borrows;
var provides;
// ,
// .
if (!data.borrows) borrows = [];
else if (data.borrows instanceof Array) borrows = data.borrows;
else borrows = [ data.borrows ];
// .
if (!data.provides) provides = [];
else if (data.provides instanceof Array) provides = data.provides;
else provides = [ data.provides ];
// , .
var proto = new superclass();
// .
for(var p in proto)
if (proto.hasOwnProperty(p)) delete proto[p];
// , .
for(var i = 0; i < borrows.length; i++) {
var c = data.borrows[i];
borrows[i] = c;
// c
196
9. ,
for(var p in c.prototype) {
if (typeof c.prototype[p] != "function") continue;
proto[p] = c.prototype[p];
}
}
//
// ,
for(var p in methods) proto[p] = methods[p];
// "constructor",
// "superclass" "classname"
proto.constructor = constructor;
proto.superclass = superclass;
// classname , .
if (classname) proto.classname = classname;
// , .
for(var i = 0; i < provides.length; i++) { //
var c = provides[i];
for(var p in c.prototype) {
//
if (typeof c.prototype[p] != "function") continue; //
if (p == "constructor" || p == "superclass") continue;
//
// . ,
if (p in proto &&
typeof proto[p] == "function" &&
proto[p].length == c.prototype[p].length) continue;
//
throw new Error(" " + classname + " "+
c.classname + "." + p);
}
}
//
constructor.prototype = proto;
//
for(var p in statics) constructor[p] = data.statics[p];
//
return constructor;
9.11 ,
defineClass().
9.11. defineClass()
// Comparable ,
// , "" Comparable.
var Comparable = defineClass({
name: "Comparable",
methods: { compareTo: function(that) { throw "abstract"; } }
});
// equals()
var GenericEquals = defineClass({
9.8. : defineClass()
name: "GenericEquals",
methods: {
equals: function(that) {
if (this == that) return true;
var propsInThat = 0;
for(var name in that) {
propsInThat++;
if (this[name] !== that[name]) return false;
}
// , this
var propsInThis = 0;
for(name in this) propsInThis++;
// ,
if (propsInThis != propsInThat) return false;
// , .
return true;
}
}
});
// Rectangle, Comparable
var Rectangle = defineClass({
name: "Rectangle",
construct: function(w,h) { this.width = w; this.height = h; },
methods: {
area: function() { return this.width * this.height; },
compareTo: function(that) { return this.area( ) that.area( ); }
},
provides: Comparable
});
// Rectangle,
// , ,
// equals().
var PositionedRectangle = defineClass({
name: "PositionedRectangle",
extend: Rectangle,
construct: function(x,y,w,h) {
this.superclass(w,h); //
this.x = x;
this.y = y;
},
methods: {
isInside: function(x,y) {
return x > this.x && x < this.x+this.width &&
y > this.y && y < this.y+this.height;
}
},
statics: {
comparator: function(a,b) { return a.compareTo(b); }
},
borrows: [GenericEquals]
});
197
JavaScript
, .
JavaS
cript . Java
Script ,
JavaScript.1
,
JavaScript. JavaScript (JavaScript Archive Network,
JSAN) Perl (Compre
hensive Perl Archive Network, CPAN), ,
JavaScript , CPAN
Perl. JSAN
http://www.openjsan.org.
JavaScript ,
,
JavaScript
,
.
.
,
,
1
JavaScript
. ,
JavaScript. JavaScript
<script src=> (. 13).
load(),
.
10.1.
199
:
, .
.
JavaScript, ,
,
, .
.
, .
10.1.
JavaScript,
,
,
. , ,
,
, .
.
JavaScript 1,
JavaScript.
provides() defineClass(), 9.8 9.10
. .
JavaScript,
.
, :
// ,
//
var Class = {};
//
Class.define = function(data) { /* */ }
Class.provides = function(o, c) { /* */ }
: (
) JavaScript.
,
.
JavaScript:
'
. :
,
.
1
, , namespace C++
Tcl ( JavaScript
). . . .
200
10.
,
, .
, Class,
Class.js, ,
:
/**
* Class.js: .
*
* "Class".
* Class ,
* .
**/
JavaScript ,
. ,
, Class
? .
,
.
.
Class.js,
.
, utilities/Class.js flanagan/Class.js.
,
. , Class,
, flanagan.Class.
:
/**
* flanagan/Class.js: .
*
* "flanagan",
* . ,
* Class flanagan.
* flanagan.Class.
**/
var flanagan; // "flanagan"
if (!flanagan) flanagan = {}; // ,
flanagan.Class = {}
// flanagan.Class
//
flanagan.Class.define = function(data) { /* */ };
flanagan.Class.provides = function(o, c) { /* */ };
flanagan
. , ,
,
flanagan.Date. ,
flanagan var
. ,
,
, unde
10.1.
201
fined. .
, undefined.
. ,
Flanagan,
, , ,
. ,
Java,
,
. ,
(.com ) ,
JavaScript
. davidflanagan.com,
com/davidflanagan/Class.js
com.davidflanagan.Class. JavaScript
,
com.davidflanagan, davidflanagan.com.
JavaScript
, .
. ,
: '
, .
10.1 com.david
flanagan.Class. ,
; ,
com.davidflanagan.Class
com com.davidflanagan, .
,
.
10.1.
// "com",
// , ,
var com;
if (!com) com = {};
else if (typeof com != "object")
throw new Error(" com , ");
//
if (!com.davidflanagan) com.davidflanagan = {}
else if (typeof com.davidflanagan != "object")
throw new Error("com.davidflanagan , ");
// , com.davidflanagan.Class
if (com.davidflanagan.Class)
throw new Error("com.davidflanagan.Class ");
//
//
202
10.
com.davidflanagan.Class = {
define: function(data) { /* */ },
provides: function(o, c) { /* */ }
};
10.1.1.
, ,
, , .
,
. ,
com .
, :
var com; //
if (!com || !com.davidflanagan || !com.davidflanagan.Class)
throw new Error("com/davidflanagan/Class.js ");
,
VERSION ,
, .
, .
10.1.2.
Class, 10.1,
.
.
, JavaScript .
10.2 ,
, .
Class define(). ( ,
, 9.10.)
10.2.
/**
* com/davidflanagan/Complex.js: ,
*
* com.davidflanagan.Complex()
* com/davidflanagan/Class.js
**/
// Class
var com; //
if (!com || !com.davidflanagan || !com.davidflanagan.Class)
throw new Error("com/davidflanagan/Class.js ");
// ,
// com.davidflanagan , .
// Complex
com.davidflanagan.Complex = com.davidflanagan.Class.define({
name: "Complex",
construct: function(x,y) { this.x = x; this.y = y; },
10.1.
203
methods: {
add: function(c) {
return new com.davidflanagan.Complex(this.x + c.x,
this.y + c.y);
}
},
});
,
. 10.3 ,
, .
10.3. ,
/**
* com/davidflanagan/Shapes.js: ,
*
* com.davidflanagan.shapes
* com/davidflanagan/Class.js
**/
// Class
var com; //
if (!com || !com.davidflanagan || !com.davidflanagan.Class)
throw new Error("com/davidflanagan/Class.js ");
//
var define = com.davidflanagan.Class.define;
//
//
//
if
,
com.davidflanagan , .
(com.davidflanagan.shapes)
throw new Error(" com.davidflanagan.shapes ");
//
com.davidflanagan.shapes = {};
// ,
//
com.davidflanagan.shapes.Circle = define ({ /* */ });
com.davidflanagan.shapes.Rectangle = define({ /* */ });
com.davidflanagan.shapes.Triangle = define ({ /* */});
10.1.3.
( ).
, ,
, .
,
.
,
, ,
. ,
,
.
204
10.
,
, :
(function() { // .
//
//
// ,
// .
})( );
// .
. .
JavaScript :
HTML
, .
,
.
, , HTML
JavaScript,
, .
( Java'
Script' 13.1.5),
, HTML
JavaScript.
,
,
.
10.5 ,
.
onload, . (
17.)
10.2.
,
com.davidflanagan.Class,
, com.davidflanagan.Class.define().
, ,
. JavaScript
,
. , com.davidflana
gan.Class :
// .
var define = com.davidflanagan.Class.define;
, .
10.2.
205
. , , ,
.
, ,
.
:
define .
,
, . :
var defineClass = com.davidflanagan.Class.define;
.
, , ,
defineClass(), define().
, .
:
// .
// , . . , , .
var Class = {};
// .
Class.define = com.davidflanagan.Class.define;
,
. : '
, , '
. ,
, ,
. ,
, .
, Class.define() ,
, com.davidflanagan.Class.counter
. ,
:
// .
// , .
Class.counter = com.davidflanagan.Class.counter;
,
, :
// ,
com.davidflanagan.Class.counter = 0;
// ,
com.davidflanagan.Class.getCounter = function() {
return com.davidflanagan.Class.counter;
}
, ,
.
206
10.
.
getCounter(). JavaScript
,
counter, ,
getCounter() .
,
. ,
, ,
. (
, 10.2.2.)
10.2.1.
, ,
. ,
,
. JavaScript ,
, .
,
.
. ,
. , ,
.
,
,
.
getCounter(), ,
counter , _counter.
,
.
, JSAN, .
, .
JSAN JSAN
, ,
, .
10.2.2.
8.8 ,
, .1
1
.
8, ,
.
10.2.
207
,
. ,
,
. . ,
,
.
,
. ,
, .
, ,
. ,
,
.
10.4.
,
.
10.4.
// .
// .
var com;
if (!com) com = {};
if (!com.davidflanagan) com.davidflanagan = {};
com.davidflanagan.Class = {};
// .
// ,
// , .
//
// com.davidflanagan.Class
// : ,
// .
(function( ) { //
//
function define(data) { counter++; /* */ }
function provides(o, c) { /* */ }
// , .
//
var counter = 0;
//
// ,
function getCounter( ) { return counter; }
// , ,
// , ,
//
var ns = com.davidflanagan.Class;
ns.define = define;
ns.provides = provides;
208
10.
ns.getCounter = getCounter;
})( ); //
10.3.
,
. Module.createNamespace()
.
:
//
Module.createNamespace("com.davidflanagan.Class");
//
com.davidflanagan.Class.define = function(data) { /* */ };
com.davidflanagan.Class.provides = function(o, c) { /* */ };
Module.require() ( )
, .
:
// Complex , Class
Module.require("com.davidflanagan.Class", 1.0);
Module.importSymbols()
.
:
// Module
// importSymbols
Module.importSymbols(Module); // ,
// ,
// Complex
importSymbols(com.davidflanagan.Complex);
// com.davidflanagan.Class.define() Class
var Class = {};
importSymbols(com.davidflanagan.Class, Class, "define");
, Module.registerInitializationFunction()
, .1
JavaScript,
,
.
( )
, Modu
le.runInitializationFunctions().
Module 10.5.
, .
.
1
17.6.
10.3.
209
10.5.
/**
* Module.js:
*
* ,
* JSAN.
* Module.
*/
// ,
var Module;
if (Module && (typeof Module != "object" || Module.NAME))
throw new Error(" 'Module' ");
//
Module = {};
//
Module.NAME = "Module";
//
Module.VERSION = 0.1;
//
// ,
// .
// ,
Module.EXPORT = ["require", "importSymbols"];
// , .
// , ,
// .
Module.EXPORT_OK = ["createNamespace", "isDefined",
"registerInitializationFunction",
"runInitializationFunctions",
"modules", "globalNamespace"];
//
Module.globalNamespace = this;
//
//
Module.modules = { "Module": Module };// Module [name]>namespace.
/**
*
*
* .
*
* , .
*
* NAME .
* version, VERSION.
*
* Module.modules
*/
Module.createNamespace = function(name, version) {
// .
//
// .
210
10.
if (!name) throw new Error("Module.createNamespace(): ");
if (name.charAt(0) == '.' ||
name.charAt(name.length1) == '.' ||
name.indexOf("..") != 1)
throw new Error("Module.createNamespace(): : " + name);
//
var parts = name.split('.');
//
// , .
var container = Module.globalNamespace;
for(var i = 0; i < parts.length; i++) {
var part = parts[i];
// ,
// .
if (!container[part]) container[part] = {};
else if (typeof container[part] != "object") {
// , ,
var n = parts.slice(0,i).join('.');
throw new Error(n + " , ");
}
container = container[part];
}
// , , , .
var namespace = container;
//
//
//
if
,
,
NAME.
(namespace.NAME) throw new Error(" "+name+" ");
//
namespace.NAME = name;
if (version) namespace.VERSION = version;
//
Module.modules[name] = namespace;
//
return namespace;
}
/**
* , .
* true, , false .
*/
Module.isDefined = function(name) {
return name in Module.modules;
};
/**
* ,
* .
* , ,
* .
* , , , .
10.3.
*/
Module.require = function(name, version) {
if (!(name in Module.modules)) {
throw new Error(" " + name + " ");
}
// ,
if (!version) return;
var n = Module.modules[name];
// , ,
// , .
if (!n.VERSION || n.VERSION < version)
throw new Error(" " + name + " " +
n.VERSION + " " + version +
" .");
};
/**
* .
* ,
* .
*
* ,
* EXPORT . , EXPORT_OK
* , from.
*
* ,
*
* , .
* EXPORT EXPORT_OK,
* , .
*/
Module.importSymbols = function(from) {
// , .
// ,
if (typeof from == "string") from = Module.modules[from];
if (!from || typeof from != "object")
throw new Error("Module.importSymbols(): " +
" ");
//
// , ,
// .
var to = Module.globalNamespace; //
var symbols = [];
//
var firstsymbol = 1;
//
// ,
if (arguments.length > 1 && typeof arguments[1] == "object") {
if (arguments[1] != null) to = arguments[1];
firstsymbol = 2;
}
//
for(var a = firstsymbol; a < arguments.length; a++)
211
212
10.
symbols.push(arguments[a]);
// , ,
// , .
if (symbols.length == 0) {
// EXPORT, .
if (from.EXPORT) {
for(var i = 0; i < from.EXPORT.length; i++) {
var s = from.EXPORT[i];
to[s] = from[s];
}
return;
}
// , EXPORT_OK ,
//
else if (!from.EXPORT_OK) {
for(s in from) to[s] = from[s];
return;
}
}
// , .
// EXPORT / EXPORT_OK,
// , ,
// . ,
// .
var allowed;
if (from.EXPORT || from.EXPORT_OK) {
allowed = {};
// .
// .
if (from.EXPORT)
for(var i = 0; i < from.EXPORT.length; i++)
allowed[from.EXPORT[i]] = true;
if (from.EXPORT_OK)
for(var i = 0; i < from.EXPORT_OK.length; i++)
allowed[from.EXPORT_OK[i]] = true;
}
//
for(var i = 0; i < symbols.length; i++) {
var s = symbols[i];
//
if (!(s in from))
//
throw new Error("Module.importSymbols(): " + s + " ");
if (allowed && !(s in allowed)) // ,
throw new Error("Module.importSymbols(): " + s +
" " +
" .");
to[s] = from[s];
//
}
};
//
// .
Module.registerInitializationFunction = function(f) {
10.3.
213
//
Module._initfuncs.push(f);
// onload , .
Module._registerEventHandler();
}
// .
// JavaScript .
// .
Module.runInitializationFunctions = function() {
// , ,
// .
for(var i = 0; i < Module._initfuncs.length; i++) {
try { Module._initfuncs[i](); }
catch(e) { /* */}
}
// , . . .
Module._initfuncs.length = 0;
}
// ,
Module._initfuncs = [];
// ,
// onload,
// .
// .
Module._registerEventHandler = function() {
var clientside =
//
"window" in Module.globalNamespace &&
"navigator" in window;
if (clientside) {
if (window.addEventListener) { // W3C DOM
window.addEventListener("load", Module.runInitializationFunctions,
false);
}
else if (window.attachEvent) { // IE5+
window.attachEvent("onload", Module.runInitializationFunctions);
}
else {
// IE4 , <body> onload,
// .
window.onload = Module.runInitializationFunctions;
}
}
// ,
// .
Module._registerEventHandler = function() {};
}
, .
RegExp JavaScript ,
String RegExp ,
.1
JavaScript ECMAScript v3. Java
Script 1.2 ,
ECMAScript v3, JavaScript 1.5.
JavaScript
Perl.
, , JavaScript 1.2
Perl 4, JavaScript 1.5 Perl 5.
,
.
String RegExp,
.
11.1.
JavaScript RegExp.
RegExp RegExp(),
. ,
, ,
,
(/). , JavaScript , :
1
. , ,
, , ,
!
regexp, RE.
11.1.
215
RegExp pattern.
RegExp , s. (
.)
RegExp():
var pattern = new RegExp("s$");
RegExp ,
RegExp() .
. JavaScript
, Perl, Perl
, , JavaScript.
. , ,
, .
/java/ , "java".
, . , /s$/
. , s, .
, $, , .
, ,
s.
,
JavaScript. ,
,
Perl, OReilly Programming Perl
(Larry Wall), (Tom Christiansen)
(Jon Orwant).1
OReilly Mastering Regular Expressions
(Jeffrey E. F. Friedl).2
11.1.1.
,
. JavaScript
,
(\).3 , \n
. . 11.1.
1
, , Perl, 3
. . . : , 2002.
, 3 . . . :
, 2008.
. .
. .
216
11.
11.1.
\0
NUL (\u0000)
\t
(\u0009)
\n
(\u000A)
\v
(\u000B)
\f
(\u000C)
\r
(\u000D)
\xnn
Latin,
nn; , \x0A , \n
\uxxxx
Unicode,
xxxx; , \u0009 , \t
\cX
^X; , \cJ
\n
:
^ $ . * + ? = ! : | \ / ( ) [ ] { }
.
, . , ,
, . 1,
@,
.
,
\, .
,
, ,
, \.
, , ,
. ,
, : /\\/.
11.1.2.
.
, . , /[abc]/
a, b c.
1
. . . .
11.1.
217
, , ,
. ^
, . /[^abc]/
, a, b c.
.
/[az]/, Latin
/[azAZ09]/.
,
JavaScript
(escape) . , \s
, (whitespaces)
Unicode, \S ,
Unicode. . 11.2
. ( :
ASCII
Unicode.
Unicode, , /[\u0400\04FF]/
.)
11.2.
[...]
[^...]
, Unicode
\w
ASCII. [azAZ09_]
\W
, ASCII.
[^azAZ09_]
\s
Unicode
\S
, Uni
code. : \w \S
\d
ASCII. [09]
\D
, ASCII. [^09]
[\b]
( )
:
. \s
, \d , , /[\s\d]/
.
. , \b .
,
. ,
, : /[\b]/.
218
11.
11.1.3.
,
/\d\d/ /\d\d\d\d/, , ,
, , ,
.
, ,
.
, , ,
. ,
. , +
.
. 11.3 .
11.3.
{n,m}
, n,
m
{n,}
, n
{n}
;
. {0,1}
.
{1,}
.a
{0,}
?, * ,
:
. ? *
.
:
/\d{2,4}/
/\w{3}\d?/
/\s+java\s+/
/[^"]*/
//
//
//
//
//
//
,
"java"
,
* ?.
, ,
. , /a*/
"bbbb", a!
11.1.
219
11.1.3.1.
, . 11.3,
,
. ,
. JavaScript 1.5 (
Perl 5, JavaScript 1.2)
, .
( ) : ??, +?, *? {1,5}?.
, /a+/
a. "aaa", .
/a+?/ a
. ,
a.
.
/a*b/, a,
b. "aaab", .
/a*?b/. b,
a.
"aaab" b.
,
. ,
,
.
,
, .
11.1.4. ,
,
. | .
, /ab|cd|ef/ ab, cd,
ef, /\d{3}|[az]{4}/ ,
.
: ,
. ,
, .
ab /a|ab/,
.
.
,
|, *, +, ?
. , /java(script)?/ java,
script, /(ab|cd)+|ef)/
ef, ab cd.
.
220
11.
, ,
, . ( ,
, .) ,
,
. /[az]+\d+/.
, .
(/[az]+(\d+)/),
.
, .
,
.
\.
. , \1 , \3
. :
, . ,
([Ss]cript)
\2:
/([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/
, , .
,
, . ,
. ,
(. .
):
/['"][^'"]*['"]/
:
/(['"])[^'"]*\1/
\1
. , ,
.
, .
, . . :
/(['"])[^\1]*\1/
,
/.
JavaScript 1.5 ( JavaScript 1.2)
.
( ) (?:
). , , :
/([Jj]ava(?:[Ss]cript)?)\sis\s(fun\w*)/
11.1.
221
(?:[Ss]cript) ,
?.
, \2 ,
(fun\w*).
. 11.4 ,
.
11.4. ,
. ,
.
(...)
. ,
*, +, ?, | . . ,
, .
(?:...)
. ,
, .
\n
,
n.
(, ).
. ,
(?:, .
11.1.5.
,
. , \s
.
, . , \b
\w ( ASCII) \W ( ),
ASCII .1
, \b, ,
,
. '
, . .
. , ^ $,
.
, JavaScript, ,
/^JavaScript$/. Java (
, JavaScript) /\sJava\s/,
2 .
. , Java,
, .
1
( ), \b
.
, . . . .
222
11.
, ,
, ,
.
\s ( ) \b.
: /\bJava\b/. \B
, . /\B[Ss]cript/
JavaScript postscript
script Scripting.
JavaScript 1.5 ( JavaScript 1.2)
.
(?= ), ,
, ,
. ,
JavaScript, , ,
/[Jj]ava([Ss]cript)?(?=\:)/. JavaScript
JavaScript: The Definitive Guide, Ja
va Java in a Nutshell, . . .
(?!,
, ,
. , /Java(?!Script)([AZ]\w*)/ Java,
ASCII, Java Script.
JavaBeans, Javanese,
JavaScrip, JavaScript JavaScripter.
. 11.5 .
11.5.
.
.
\b
, . .
\w \W \w .
( , [\b] .)
\B
, .
(?=p)
. ,
p,
.
(?!p)
. ,
p.
11.1.6.
, .
.
11.2. String
223
,
, . JavaScript 1.2
. i ,
, g ,
. . .
.
,
java ( Java, JAVA . .),
/\bjava\b/i.
, g: /\bjava\b/gi.
JavaScript 1.5 m,
. ,
, ,
^ $, ,
, . ,
/Java$/im java, Java\nis fun.
. 11.6 . ,
g
String RegExp, .
11.6.
, .
, . . ,
.
. ^
, $ .
11.1.7. Perl,
JavaScript
, ECMAScript v3
Perl 5. Perl,
ECMAScript, :
s ( ) x ( );
\a, \e, \l, \u, \L, \U, \E, \Q, \A, \Z, \z \G;
(?<= (?<!
;
(?# (?.
11.2. String
, ,
JavaScript.
224
11.
String,
, .
JavaScript, RegExp,
. :
, .
, .
, .
search().
, 1, . ,
4:
"JavaScript".search(/script/i);
search() ,
RegExp. search()
g .
replace() .
, .
, , .
g, replace()
,
. replace()
, ,
,
RegExp(), search().
replace()
JavaScript :
//
text.replace(/javascript/gi, "JavaScript");
replace() ,
. , ,
, ,
, .
$ , replace()
, .
. , ,
, ASCII
:
// , ,
// ( ),
// .
var quote = /"([^"]*)"/g;
//
// , $1.
text.replace(quote, "``$1''");
replace() ,
String.replace().
11.2. String
225
, , replace()
, .
match() String,
.
( ,
RegExp()) ,
. g,
, . :
"1 2 3".match(/\d+/g) // ["1", "2", "3"]
g, match()
; . match()
, .
,
. match()
a, a[0] , a[1]
, , . .
replace(), , a[n] $n.
,
URL:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = " http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // "http://www.isp.com/~david"
var protocol = result[1]; // "http"
var host = result[2];
// "www.isp.com"
var path = result[3];
// "~david"
}
, match(),
. , , length.
match() g,
: index,
, , input,
, .
result.index 31, . . URL
31 . result.input ,
text. r,
g, s.match(r) , r.exec(s).
RegExp.exec().
String,
, split(). , ,
, . :
"123,456,789".split(","); // ["123","456","789"]
split()
. . ,
, :
226
11.
split() .
String.split().
11.3. RegExp
,
RegExp. RegExp(), RegExp
. RegExp
, ( ),
. ,
RegExp(), ,
RegExp. RegExp
.
RegExp()
RegExp. ,
, . . ,
. :
\, Re
gExp() ,
\ \\. RegExp() .
, .
g, i, m . :
// .
// \\
var zipcode = new RegExp("\\d{5}", "g");
RegExp() ,
. , ,
,
RegExp().
11.3.1. RegExp
RegExp , ;
String, .
RegExp, , exec().
match() String, ,
RegExp, ,
String, RegExp. exec()
, . . .
, null.
, , , match()
g. ,
, ,
. , index
11.3. RegExp
227
, ,
input , .
match(), exec() ,
g. ,
match()
. exec() ,
. exec()
, g, lastIndex
,
. exec()
, ,
lastIndex. exec() ,
lastIndex 0. ( lastIndex
, ,
,
RegExp.)
exec()
. :
var pattern = /Java/g;
var text = "JavaScript , Java!";
var result;
while((result = pattern.exec(text)) != null) {
alert(" `" + result[0] + "'" +
" " + result.index +
"; " + pattern.lastIndex);
}
228
11.
, . , ,
lastIndex g.
exec() test() lastIndex RegExp,
g.
11.3.2. RegExp
RegExp . source
, . glo
bal , ,
g. ignoreCase
, ,
i. multiline
, , m.
lastIndex ,
. g ,
.
, exec() test().
Java
JavaScript Java.
, ,
C.
. JavaScript
, Java.1
Java 6, Java
Script, JavaScript Java
. , JavaScript ( ,
Java 6) ,
JavaScript Java,
.
, JavaScript
, Java 6, JavaScript
. ,
Java JavaScript.
Java 23, Java
Java .
12.1. JavaScript
, Java
Script. Java
Script . ,
1
Java,
Java.
, .
230
12. Java*
JavaScript .
JavaScript
. Firefox, ,
JavaScript.
, ,
.
Mozilla JavaScript,
. SpiderMonkey
JavaScript, C. Rhino
Java.
.
JavaScript , ,
SpiderMonkey. Java
, Rhino.
http://www.mozilla.org/js/spidermonkey http://www.mozilla.org/rhino.
Java 6.0 JavaScript
Java.
. Java 6 javax.script,
,
JavaScript Rhino, .1
12.1 javax.script:
ScriptEngine,
JavaScript, Bindings, Java
Script. ,
, java.io.Reader
Bindings eval() ScriptEngine. eval()
ScriptException,
.
12.1. Java, JavaScript'
import javax.script.*;
import java.io.*;
// JavaScript
public class RunScript {
public static void main(String[] args) throws IOException {
// , "ScriptEngine", .
ScriptEngineManager scriptManager = new ScriptEngineManager();
ScriptEngine js = scriptManager.getEngineByExtension("js");
//
String filename = null;
1
Java 6
. javax.script ,
, ,
.
12.1. JavaScript
231
// Bindings , ,
// .
// .
Bindings bindings = js.createBindings( );
// .
// Dname=value, .
// , D,
for(int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("D")) {
int pos = arg.indexOf('=');
if (pos == 1) usage();
String name = arg.substring(2, pos);
String value = arg.substring(pos+1);
// : .
// .
// , java.lang.Number,
// java.lang.Boolean Java null.
bindings.put(name, value);
}
else {
if (filename != null) usage();//
filename = arg;
}
}
// , .
if (filename == null) usage();
//
// ,
// , .
// .
bindings.put(ScriptEngine.FILENAME, filename);
// .
Reader in = new FileReader(filename);
try {
// , , .
Object result = js.eval(in, bindings);
// .
System.out.println(result);
}
catch(ScriptException ex) {
// .
System.out.println(ex);
}
}
static void usage() {
System.err.println(
" : java RunScript [Dname=value...] script.js");
System.exit(1);
}
}
232
12. Java*
Bindings, ,
, JavaScript, .
12.2 Java.
Bindings ScriptContext
, ,
Bindings .
:
/,
Configuration.
, ,
, JavaScript . ,
java.util.Map, /, SimpleBin
dings, JavaScript
, .1
12.2. ,
JavaScript'
import javax.script.*;
import java.util.*;
import java.io.*;
/**
* java.util.Properties,
* JavaScript.
*/
public class Configuration {
// /
Map<String,Object> defaults = new HashMap<String,Object>( );
//
public Object get(String key) { return defaults.get(key); }
public void put(String key, Object value) { defaults.put(key, value); }
// Map /.
// ,
// JavaScript.
public void load(String filename) throws IOException, ScriptException {
//
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
// / JavaScript.
Bindings bindings = new SimpleBindings(defaults);
// .
ScriptContext context = new SimpleScriptContext();
, JavaScript
.
Java,
, .
Java .
12.1. JavaScript
// , ,
// , , Map
context.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine( )) != null) {
line = line.trim( ); //
if (line.length( ) == 0) continue; //
if (line.charAt(0) == '#') continue; //
int pos = line.indexOf(":");
if (pos == 1)
throw new IllegalArgumentException("syntax: " + line);
String name = line.substring(0, pos).trim();
String value = line.substring(pos+1).trim();
char firstchar = value.charAt(0);
int len = value.length( );
char lastchar = value.charAt(len1);
if (firstchar == '"' && lastchar == '"') {
//
defaults.put(name, value.substring(1, len1));
}
else if (Character.isDigit(firstchar)) {
// ,
//
try {
double d = Double.parseDouble(value);
defaults.put(name, d);
}
catch(NumberFormatException e) {
// . .
defaults.put(name, value);
}
}
else if (value.equals("true")) //
defaults.put(name, Boolean.TRUE);
else if (value.equals("false"))
defaults.put(name, Boolean.FALSE);
else if (value.equals("null"))
defaults.put(name, null);
else if (firstchar == '{' && lastchar == '}') {
// JavaScript
String script = value.substring(1, len1);
Object result = engine.eval(script, context);
defaults.put(name, result);
}
else {
//
defaults.put(name, value);
}
}
}
233
234
12. Java*
//
public static void main(String[] args) throws IOException, ScriptException
{
Configuration defaults = new Configuration();
defaults.load(args[0]);
Set<Map.Entry<String,Object>> entryset = defaults.defaults.entrySet();
for(Map.Entry<String,Object> entry : entryset) {
System.out.printf("%s: %s%n", entry.getKey(), entry.getValue());
}
}
12.1.1.
javax.script
, ,
, ,
, ,
.1 ,
java.lang.String java.lang.Integer Bindings. Java
Script ,
? JavaScript
, eval()?
Java JavaScript .
Bindings Java (
), JavaScript
:
JavaScript.
java.lang.Number JavaScript.
. Java
JavaScript. Byte, Short, Integer, Long,
Float, Double, java.math.BigInteger java.math.BigDouble.
, Infinity NaN,
. , JavaScript
64
1
, ,
.
. .
. .
12.1. JavaScript
235
12.1.2.
( ),
, .
, , :
// , .
String scripttext = "x * x";
// .
ScriptEngineManager scriptManager = new ScriptEngineManager( );
ScriptEngine js = scriptManager.getEngineByExtension("js");
// Compilable, .
Compilable compiler = (Compilable)js;
// , .
//
CompiledScript script = compiler.compile(scripttext);
// , x
Bindings bindings = js.createBindings( );
for(int i = 0; i < 5; i++) {
bindings.put("x", i);
Object result = script.eval(bindings);
System.out.printf("f(%d) = %s%n", i, result);
}
236
12. Java*
12.1.3. JavaScript
javax.script
, , .
, , :
// , "ScriptEngine",
ScriptEngineManager scriptManager = new ScriptEngineManager();
ScriptEngine js = scriptManager.getEngineByExtension("js");
// . ,
// .
js.eval("function f(x) { return x*x; }");
// , .
try {
// ScriptEngine Invokable,
// .
Invocable invocable = (Invocable) js;
for(int i = 0; i < 5; i++) {
Object result = invocable.invoke("f", i);
// f(i)
System.out.printf("f(%d) = %s%n", i, result); //
}
}
catch(NoSuchMethodException e) {
// ,
// "f".
System.out.println(e);
}
12.1.4. JavaScript
Invocable, ,
JavaScript.
12.3 JavaScript listener.js
java.awt.event.KeyListener.
12.3. Java' JavaScript'
import
import
import
import
javax.script.*;
java.io.*;
java.awt.event.*;
javax.swing.*;
12.2. Java*
237
// KeyListener
// .
JFrame frame = new JFrame("Keys Demo");
frame.addKeyListener(listener);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
JavaScript
, ,
. , KeyListener:
function keyPressed(e) {
print(" : " + String.fromCharCode(e.getKeyChar()));
}
function keyReleased(e) { /* */ }
function keyTyped(e)
{ /* */ }
: JavaScript keyPressed()
java.awt.event.KeyEvent
Java. , .
12.2. Java
JavaScript
Java.
Bindings,
Java , JavaScript.
Java,
Java. Netscape ,
JavaScript Java
, SpiderMonkey
Java . Netscape
LiveConnect. Rhino, JScript,
Microsoft,
LiveConnect, LiveConnect
, JavaScript Java.
LiveConnect.
LiveConnect.
: Rhino SpiderMonkey
LiveConnect. , ,
Rhino ,
Java 6. SpiderMonkey,
, 23.
Java JavaScript Bindings
, JavaScript
, JavaScript.
Java
JavaScript. , , Java,
238
12. Java*
. ,
lineColor String, JavaScript
chart. JavaScript
:
var chartcolor = chart.lineColor; // Java.
chart.lineColor = "#ff00ff";
// Java.
, JavaScript .
, (
Java):
public int numPoints;
public double[] points;
JavaScript :
for(var i = 0; i < chart.numPoints; i++)
chart.points[i] = i*i;
Java, JavaScript
. , ,
redraw().
, points[]
. JavaScript ,
JavaScript:
chart.redraw();
, JavaScript
.
. ,
:
public void setDomain(double xmin, double xmax);
public void setChartTitle(String title);
public String getXAxisLabel();
JavaScript :
chart.setDomain(0, 20);
chart.setChartTitle("y = x*x");
var label = chart.getXAxisLabel();
, Java
Java, JavaScript
. , Java
Script Java Java.
, getXAxis(),
Java Axis.
, setYAxis(),
Axis. , ,
Axis setTitle().
JavaScript :
var xaxis = chart.getXAxis(); // Axis
var newyaxis = xaxis.clone(); //
12.2. Java*
newyaxis.setTitle("Y");
chart.setYAxis(newyaxis);
239
// ...
// ...
LiveConnect , . . JavaScript
new Java
. JavaScript,
Java Swing:
// javax.*
var javax = Packages.javax;
// Java.
var frame = new javax.swing.JFrame("Hello World");
var button = new javax.swing.JButton("Hello World");
var font = new java.awt.Font("SansSerif", java.awt.Font.BOLD, 24);
// .
frame.add(button);
button.setFont(font);
frame.setSize(200, 200);
frame.setVisible(true);
, LiveConnect JavaScript
Java, , JavaScript
LiveConnect. .
12.2.1. JavaPackage
Java Java
. JavaPackage JavaScript,
Java. JavaPackage (
JavaClass, ),
, . JavaPackage
, for/in
.
JavaPackage JavaPackage.
Packages JavaPackage ,
.
, java javax,
JavaPackage, Java,
. , JavaPackage Pack
240
12. Java*
12.2.2. JavaClass
JavaClass JavaScript, Java.
JavaClass :
Java.
, , ,
. JavaPackage, JavaClass
for/in. ,
JavaClass ,
Java, Java
JavaObject, .
, JavaClass
JavaPackage. , java.lang JavaPackage
System. , java.lang.System JavaClass,
Java java.lang.System. JavaClass
, out in,
java.lang.System. JavaScript
Java. ,
java.lang.Double java.lang.Double ( Packages.java.lang.Double),
javax.swing.JButton Packages.javax.swing.JButton.
JavaScript JavaClass
getClass(). getClass()
JavaObject, JavaClass,
Java .1
1
12.2. Java*
241
JavaClass ,
. JavaClass LiveConnect,
JavaScript
Java
Java. , java.lang.System
JavaClass, java.lang.System
:
var java_console = java.lang.System.out;
java.lang.System:
var java_version = java.lang.System.getProperty("java.version");
, Java :
, .
, .
JavaClass .
JavaClass new
Java, . . JavaObject. JavaScript
( Java)
JavaScript:
var d = new java.lang.Double(1.23);
, JavaObject ,
getClass() , :
var d = new java.lang.Double(1.23); // JavaObject
var d_class = getClass(d);
// JavaClass JavaObject
if (d_class == java.lang.Double) ...; // true
JavaClass
, java.lang.Double, ,
:
var Double = java.lang.Double;
import
Java , . . LiveConnect
lang java, Double java.lang.
12.2.3.
LiveConnect Rhino
, Java Java.
JavaPackage importPackage(),
JavaClass importClass():
importPackage(java.util);
importClass(java.awt.List);
importClass() JavaClass
JavaPackage . importClass()
:
var List = java.awt.List;
242
12. Java*
importPackage() JavaClass
JavaPackage . ( )
,
, JavaClass,
. ,
importPackage() Java
Script Map. Map,
java.util.Map JavaClass
Map .
, java.lang im
portPackage() , java.lang
,
JavaScript.
JavaPackage :
var swing = Packages.javax.swing;
12.2.4. JavaObject
JavaObject JavaScript, Java.
JavaObject JavaClass. JavaClass,
JavaObject
( )
Java, .
JavaClass, JavaObject
for/in. JavaObject LiveCon
nect,
Java.
, , d JavaObject,
java.lang.Double, Java Java
Script :
n = d.doubleValue();
, java.lang.System out.
Java java.io.PrintStream. JavaScript
JavaObject :
java.lang.System.out
:
java.lang.System.out.println("Hello world!");
, JavaObject
Java, .
java.lang.Double, java.io.PrintStream
, , JavaScript
java.awt.Rectangle:
12.2. Java*
243
r = new java.awt.Rectangle( );
JavaScript
:
r.x = r.y = 0;
r.width = 4;
r.height = 5;
var perimeter = 2*r.width + 2*r.height;
LiveConnect ,
Java ,
JavaScript. :
r JavaObject, ,
JavaScript ( ). ,
, JavaScript, Java
Java . JavaScript
1, JavaScript .
12.2.5. Java
LiveConnect Java JavaScript
, Java , ,
JavaScript. ,
, ,
Java. Java
JavaScript,
:
var isDigit = java.lang.Character.isDigit;
12.2.5.1.
Java LiveConnect Rhino
, JavaBeans
( /), Li
veConnect ,
JavaScript. , javax.swing.JFrame ja
vax.swing.JButton, . JButton
setFont() getFont(), JFrame setVisible() getVisible(). Live
Connect , , , JButton
font, JFrame visible. :
button.setFont(font);
frame.setVisible(true);
:
1
JavaScript
JavaObject,
Java,
. . . .
244
12. Java*
button.font = font;
frame.visible = true;
12.2.5.2.
Java .
JavaObject,
,
. LiveConnect
, .
,
. JavaOb
ject JavaClass ,
, .
, JavaObject,
f, int, boolean.
o.f ,
Java, .
, Java :
var f = o['f'];
//
var boolfunc = o['f(boolean)']; // boolean
var intfunc = o['f(int)'];
// int
,
.
, JavaClass
.
12.2.6. JavaArray
LiveConnect JavaScript JavaArray.
,
Java LiveConnect,
Java JavaScript. JavaScript Java
, JavaArray length,
, .
JavaArray [].
, for/in.
JavaArray (
) , JavaScript Java.
java.awt.Polygon:
p = new java.awt.Polygon( );
12.2. Java*
for(var i = 0; i
p.xpoints[i]
for(var i = 0; i
p.ypoints[i]
<
=
<
=
245
p.xpoints.length; i++)
Math.round(Math.random( )*100);
p.ypoints.length; i++)
Math.round(Math.random( )*100);
12.2.6.1. Java
LiveConnect Java
JavaScript Java.
Java,
java.lang.reflect:
var p = new java.awt.Polygon();
p.xpoints = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE,5);
p.ypoints = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE,5);
for(var i = 0; i < p.xpoints.length; i++) {
p.xpoints[i] = i;
p.ypoints[i] = i * i;
}
12.2.7. LiveConnect
LiveConnect Rhino JavaScript
Java :
JavaClass
JavaScript,
. , ,
,
, :
// , .
importClass(Packages.javax.swing.JFrame);
importClass(Packages.javax.swing.JButton);
importClass(java.awt.event.ActionListener);
// Java.
var frame = new JFrame("Hello World");
var button = new JButton("Hello World");
// ActionListener.
var listener = new ActionListener({
actionPerformed: function(e) { print("Hello!"); }
});
// .
button.addActionListener(listener);
// .
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
12.2.8. LiveConnect
Java ,
. JavaScript
246
12. Java*
, .
,
LiveConnect
. JavaScript
Java Java, JavaScript
Java.
JavaScript Java
Java, Java
JavaScript. ,
LiveConnect , javax.script.
12.1 12.2
JavaScript Java, .
,
. 12.1:
Java
Script Java, Java
Script Java JavaScript.
, JavaScript Java,
java.lang.String, JavaScript
, Java.
JavaScript
Java. ,
Java Java. :
, ,
Java short
Java.
12.2. Java*
247
JavaScript Java
java.lang.Double, ,
java.lang.Integer java.lang.Float.
JavaScript ,
JavaScript Java char.
JavaScript Java JavaObject,
1, Java,
. JavaClass JavaScript
java.lang.Class, .
JavaScript Java. ,
JavaScript Java,
.
, . 12.2,
:
JavaScript ,
Java char JavaScript,
, .
, JavaObject
Java. . . .
248
12. Java*
java.lang.Double, java.lang.Integer
JavaScript. Java,
JavaObject.
Java java.lang.String,
, Java,
JavaObject, JavaScript.
: JavaScript length.
JavaObject, java.lang.String,
length, length()
Java.
JavaObject java.lang.Boolean.FALSE.
false, true!
, JavaObject null. ,
, .
JavaScript
13 23 JavaScript ,
.
JavaScript, , HTML
XML.
13 JavaScript
14
15
16 CSS DHTML
17
18
19 Cookies
20 HTTP
21 JavaScript XML
22
23 Java Flash
JavaScript
JavaScript.
JavaScript,
JavaScript (clientside JavaScript).1
, , JavaScript,
; JavaScript,
.
.
JavaScript.
, JavaScript
HTML JavaScript <script>, HTML
URL. ,
JavaScript,
, , JavaScript
.
JavaScript: , .
JavaScript,
, JavaScript.
JavaScript
, .
JavaScript.
14 , JavaScript
, ,
252
13. JavaScript *
, URL
.
JavaScript,
Window.
15 , JavaScript
, , ,
, .
16 CSS DHTML Java
Script CSS, , JavaScript
, CSS,
.
CSS HTML ( DHTML),
HTML ,
, .
17
, , JavaScript
, .
18 HTML.
, JavaScript , ,
, .
19 Cookies
,
cookies.
20 HTTP
HTTP (, Ajax) ,
JavaScript .
21 JavaScript XML , , ,
, XML,
.
22
,
.
JavaScript.
23 Java Flash ,
JavaScript Java Flash
, .
13.1.
, JavaScript,
,
.
:
Window,
JavaScript;
13.1. *
253
(DOM),
;
.
JavaScript
.
13.1.1.
HTML .
JavaScript Document HTML,
Window ( ),
. JavaScript , Window
.
4, JavaScript
;
. JavaScript
Window . Window
, .
, ,
document Document. , Window
window self.
Window.
Window JavaScript,
. ,
:
var answer = 42;
//
window.answer = 42; // Window
Window ( ;
JavaScript
). ,
( ).
Window
JavaScript. , , JavaScript
, . JavaScript
,
.
14.
13.1.2. JavaScript
, Window JavaScript.
. , Window
document, Document,
location, Location.
Window frames[], Window,
254
13. JavaScript *
. document Docu
ment , frames[1].document Document
.
Document ( JavaScript)
, . ,
Document forms[], Form,
HTML.
:
window.document.forms[0]
: Form elements[],
, HTML
( , . .), .
,
, , , :
parent.frames[0].document.forms[0].elements[3].options[2].text
, Window
, JavaScript
. , JavaScript,
Window. . 13.1.
: . 13.1 ,
. , ,
, .
13.1. *
255
, , Docu
ment.
(Document Object Model, DOM) ,
.
, , . .
.
DOM (DOM Level 0),
, JavaScript
. 15,
,
W3C. HTML DOM,
, 18.
13.1.3.
, , .
, .
.
,
, .
,
,
. . HTML
(GUI), JavaScript
.
JavaScript,
.
. ,
. ,
.
JavaScript
, . ,
, . . ,
. ,
JavaScript
, .
, ,
, .
,
.
.
( ) .
256
13. JavaScript *
,
. ,
, , .
, ,
.
, JavaScript HTML
, ,
, , .
15,
17.
13.1.5. JavaScript
, '
JavaScript' (unobtrusive JavaScript),
.
, , JavaScript
, . . .1 JavaScript
1
. The American Heritage dictionary:
.
13.1. *
257
, , ,
HTML, , HTML
CSS.
,
JavaScript. ,
, .
JavaScript
HTML. ,
, CSS , . .
. JavaScript
, HTML
<script src=> ( . 13.2.2).
,
JavaScript HTML.
JavaScript ,
HTML
( , , 17).
, Java
Script , ,
, 10.
, ,
.
JavaScript ,
.
HTML,
JavaScript (,
JavaScript).
, (feature testing):
, JavaScript ,
, ,
, .
13.6.3.
JavaScript ,
HTML ( ).
JavaScript ,
JavaScript
, .
JavaScript 13.7.
JavaScript
.
JavaScript The JavaScript Manifesto,
DOM Scripting Task Force http://
domscripting.webstandards.org/?page_id=2.
258
13. JavaScript *
13.2. JavaScript
HTML
JavaScript HTML
:
<script> </script>;
, src <script>;
, HTML,
onclick onmouseover;
URL,
javascript:.
<script>. JavaScript
URL .
13.2.1. <script>
JavaScript HTML
<script> </script>:
<script>
// JavaScript
</script>
XHTML <script>
. JavaScript < &,
XML.
XHTML JavaScript CDATA:
<script><![CDATA[// JavaScript
]]></script>
HTML
<script>. ,
( defer,
13.2.4).
, HTML
JavaScript: ,
, ,
. , HTML :
<script>function square(x) { return x*x; }</script>
HTML square(),
. HTML,
:1
1
alert() :
.
alert() 14.5. 15.9
alert(), ,
.
259
<script>alert(square(2));</script>
13.1 docu
ment.write(). JavaScript
HTML , (
15). :
HTML ,
HTML Java
Script .
, , ,
( defer 13.2.4).
13.2.2.
<script> src. URL
, JavaScript. :
<script src="../../javascript/util.js"></script>
260
13. JavaScript *
. , </script>
, src JavaScript.
src :
HTML , . .
JavaScript, . src
Java
Script ( 13.1.5).
JavaScript JavaScript,
HTML,
.
.
JavaScript ,
. JavaScript
, ,
, ,
JavaScript
.
src URL,
JavaScript
(, ),
.
,
. , 13.8.2,
. ,
,
, . ,
: JavaScript
, ,
, .
src, (
, ) .
13.2.3.
JavaScript
, . HTML
,
.
JavaScript Visual Basic Scripting
Edition Microsoft1, Internet Explorer.
1
261
, , .
,
, .
HTTP ContentScriptType.
HTML <meta>.
, JavaScript ( ),
<head> HTML:
<meta httpequiv="ContentScriptType" content="text/javascript">
, JavaScript
, ContentScriptType
<meta>.
,
type <script>:
<script type="text/javascript"></script>
<script> ,
HTML type.
language:
<script language="JavaScript">
// JavaScript
</script>
VBScript,
:
<script language="VBScript">
' VBScript (' , // JavaScript)
</script>
262
13. JavaScript *
language JavaScript,
:
<script language="JavaScript1.2"></script>
<script language="JavaScript1.5"></script>
,
JavaScript. , ,
JavaScript 1.5, , lan
guage "JavaScript1.5".
, JavaScript
,
, language.
13.2.4. defer
, document.write()
. HTML
, ,
. HTML 4
defer <script>, .
,
document.write(), ,
defer <script> ,
HTML ,
, .
,
; ,
.
, defer. HTML
defer ; :
<script defer>
// JavaScript, document.write()
</script>
XHTML :
<script defer="defer"></script>
Internet Explorer
, defer. ,
<script> src.
, defer
, ,
, .
, IE ,
.
, ,
, .
263
13.2.5. <noscript>
HTML <noscript>,
, ,
JavaScript.
, JavaScript
,
. , <noscript>
, JavaScript , ,
.
13.2.6. </script>
document.write()
innerHTML (
).
</script>. HTML
JavaScript, "/script" ,
,
. , ,
, "</" + "script>", :
<script>
f1.document.write("<script>");
f1.document.write("document.write('<h2> </h2>')");
f1.document.write("</" + "script>");
</script>
/ </script>
:
f1.document.write("<\/script>");
XHTML CDATA
</script> .
13.2.7.
JavaScript ,
<script> ( ) ,
. , , JavaScript
,
! , <script>
HTML.
:
<script language="JavaScript">
<! HTML,
// JavaScript
//
.
//
.
// HTML, >
</script>
264
13. JavaScript *
:
<script><!
//
//></script>
JavaScript,
<!
//.
,
, ,
.
13.2.8. <script>
Microsoft
<script>, Internet Explorer. event for
<script>. event
, for ,
(ID), , .
, .
IE,
.
,
, .
13.3. HTML
JavaScript, <script>, ,
HTML .
.
,
,
. JavaScript
HTML ( ),
. , ,
, ,
HTML, :
<input type="checkbox" name="options" value="gifwrap"
onclick="gifwrap = this.checked;"
>
onclick. onclick
JavaScript.
, .
(
), JavaScript, .
Java
Script,
13.3. HTML
265
, <script>
</script>. JavaScript
<script> JavaScript HTML.
,
JavaScript. 17 ,
HTML,
JavaScript <script>. JavaScript
HTML
,
JavaScript,
. Java
Script ,
src <script>. JavaScript
,
.
17,
.
17 ,
:
onclick
,
, <a> <area>. ,
. onclick false,
, , ,
( <a>) (
Submit).
onmousedown, onmouseup
onclick,
, .
.
onmouseover, onmouseout
,
.
onchange
<input>, <select> <text
area>. , ,
,
.
onload
<body>.
, (,
) . onload
,
, . . ,
.
266
13. JavaScript *
1.3. HTML
. :
calculate(),
<script>.
URL,
JavaScript
.
HTML, ,
, .
URL JavaScript JavaScript,
, . :
javascript:alert("Hello World!")
URL, JavaScript,
. . ,
.
javascript: URL
. , URL
.
, void
. URL
javascript: :
void 0;
, , URL,
:
javascript:window.open("about:blank"); void 0;
void URL ,
Window.open(), ,
,
:
[object Window]
267
URL javascript: ,
URL.
.
JavaScript
HTML .
javascript: HTML
, URL. href
. ,
JavaScript. URL
javascript: , , onclick. (
, onclick URL
javascript: HTML
;
,
.) URL javascript:
action <form>
JavaScript.
URL javascript: ,
Window.open() ( . 14),
URL .
13.4.1.
URL
javascript: ,
JavaScript, (bookmarklet).
.
href <a>,
URL javascript:.
JavaScript,
:
<a href='javascript:
var e = "", r = ""; /* */
do {
/* , */
e = prompt(": " + e + "\n" + r + "\n", e);
try { r = ": " + eval(e); } /* */
catch(ex) { r = ex; }
/* */
} while(e); /* , , */
/* */
void 0;
/* */
'>
JavaScript
</a>
: ,
, ,
(//) .
:
268
13. JavaScript *
, , ,
, , ,
.
. Firefox
.
JavaScript,
,
, .
,
bookmarklets. ,
.
13.5. JavaScript
JavaScript
HTML. , JavaScript
JavaScript.
13.5.1.
JavaScript, <script> </script>,
.
, , (
defer IE
). JavaScript
.
<script>, defer,
document.write() ( 15). , ,
,
. ,
HTML, , .
<head> <body> HTML.
<head> ,
. ,
. <head>
,
onload .
, , document.write()
<head>.
<body> ,
<head>. document.write().
, <body> , (
, 15)
13.5. JavaScript*
269
, , . ,
, ,
<body>, .
document.write() ,
<head>,
<body>.
, IE defer
. ,
, ,
onload.
13.5.2. onload
,
(, ) ,
onload JavaScript,
onload Window.
onload onload <body>.
JavaScript
onload ( ,
17).
onload, , ,
, .
onload
,
JavaScript. Java
Script, ,
, , ,
onload.
, .
onload ,
, document.write().
,
,
, .
270
13. JavaScript *
<script> ,
, , .
, ,
.
document.write() ,
, .
, ,
, .
,
write() . (
14.8.)
13.5.4. onunload
,
onunload, JavaScript
. onunload
<body> onunload,
, 17.
onunload ,
onload . , JavaScript
, onunload
, , ,
. onunload
.
,
.
13.5.5. Window
, URL JavaScript
Window.
JavaScript .
, , <script>,
<script>.
onload ,
, onload
,
.
, , Window
: ,
,
.
.
,
. , , ,
, ,
.
13.5. JavaScript*
271
Window ,
JavaScript . Window
,
. Window
,
. ,
. JavaScript
,
, .
13.5.6.
JavaScript
JavaScript
, JavaScript
. JavaScript
. ,
,
.
: , ,
.
, ,
.
, . . JavaScript
.
, ,
, .
,
,
, .1
,
,
. ,
, ,
.
, ,
, setTimeout() setInterval(),
,
(. 14).
, Firefox,
.
,
, ,
.
272
13. JavaScript *
13.5.7.
JavaScript, <script>,
window.write().
, DOM
15, <script>
.
,
<script>. JavaScript
.
, JavaScript ,
, ,
<script>, ( ,
,
).
, , ,
onload,
JavaScript
onload
. ,
onload, 17.7.
,
,
onload.
onload. ( )
, . IE
<script> defer src,
Firefox
DOMContentLoad, ,
, .
JavaScript ,
,
? JavaScript
,
, . ,
.
,
(
) ,
onload.
, , . ,
,
.
13.6.
273
13.6.
, Ja
vaScript ,
. , JavaScript
ECMAScript v3. , , . ,
HTML,
, CSS DOM.
Ja
vaScript, (Applicati
on Programming Interface, API), JavaScript.
, JavaScript.
JavaScript
.
: Internet Explorer
Windows Mac OS1; Firefox Windows, Mac OS Linux; Safari Mac OS
Opera Windows, Mac OS Linux.
, ,
, 27
, . ,
27 ,
. ,
.
,
.
JavaScript
.
,
, .
,
JavaScript.
,
:
http://www.quirksmode.org/dom/
(PiterPaul Koch).
DOM
W3C DOM.
http://webdevout.net/browser_support.php
(David Hammond). quirksmo'
de.org, (
1
IE Mac OS , ,
IE Windows.
274
13. JavaScript *
) .
DOM
HTML, CSS ECMAScript.
, .
,
, .
13.6.1.
JavaScript
.
, , , .
Netscape
Microsoft. API
JavaScript, .
,
,
.
, Microsoft
, , CSS DOM,
. ( ),
, Netscape Firefox, Microsoft
.
, , ,
.
, ,
. ,
HTTP,
Ajax ( . 20).
Microsoft 7
Internet Explorer,
CSS. IE 7
, ,
, .
. , Safari Firefox
<canvas>,
( . 22).
( , , Microsoft ),
WHATWG (whatwg.org), <can
vas> HTML DOM.
13.6.2.
JavaScript , ,
.
. , , ,
. ,
13.6.
275
,
.
, ,
(
, IE).
: Firefox 1.0, Firefox 1.5, IE 5.5, IE 6.0, Safari 2.0,
Opera 8 Opera 8.5. ,
. ,
.
13.6.3.
( '
) ,
. , ,
, ,
,
.
,
,
, .
,
. , 17 ,
:
if (element.addEventListener) { // W3C
element.addEventListener("keydown", handler, false);
element.addEventListener("keypress", handler, false);
}
else if (element.attachEvent) { // IE
element.attachEvent("onkeydown", handler);
element.attachEvent("onkeypress", handler);
}
else { //
element.onkeydown = element.onkeypress = handler;
}
20 :
, ,
!
. 20.1:
// XMLHttpRequest,
HTTP._factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
// ,
HTTP._factory = null;
276
13. JavaScript *
// XMLHttpRequest.
//
// ,
// ,
// . ,
// .
HTTP.newRequest = function() { /* */ }
DOM, ,
,
.
DHTML, :
if (document.getElementById) { // W3C DOM API,
// DHTML, W3C DOM API
}
else if (document.all) {
// IE 4 API,
// DHTML, IE 4 API
}
else if (document.layers) { // Netscape 4 API,
// DHTML (, )
// Netscape 4 API
}
else { // DHTML ,
// DHTML
}
,
W3C DOM document.getElementById().
, , ,
.
, ,
,
. ,
,
. Microsoft addEventHandler(),
W3C ,
, addEventHand
ler() .
document.all, ,
. document.all Microsoft IE 4.
JavaScript
.
document.getElementById().
(
) , ,
IE :
if (document.all) {
// IE
}
else {
13.6.
277
//
}
,
document.all, Firefox
, Firefox ,
IE. all
, Firefox
. , , Firefox docu
ment.all, if ,
all ,
Firefox.
if (document.all) alert("IE"); else alert("Firefox");
,
, ! ,
, ,
.
.
13.6.4.
. ,
, , ,
W3C IE. ,
, ,
.
,
,
( ).
Navigator,
14. ,
, (browser sniffer),
(client sniffer).
14.3.
, Netscape
IE .
,
, .
,
,
, UserAgent, ,
JavaScript .
278
13. JavaScript *
IE
.
, , IE
JavaScript,
.
,
HTML. ,
, .
<![if IE]>
HTML.
IE.
<![endif]>
<![if gte IE 6]>
IE 6 .
<![endif]>
<![if !IE]> <>
HTML, IE
, .
<!> <![endif]>
, .
JavaScript IE,
, C/C++,
#ifdef/#endif. JavaScript IE
/*@cc_on @*/. (
cc cc_on condition compilation, . .
.)
, IE:
/*@cc_on
@if (@_jscript)
// JS, IE .
alert("In IE");
@end
@*/
@if, @else
@end, ,
JavaScript IE .
@if (@_jscript). JScript Java
Script, Microsoft, @_jscript IE
true.
JavaScript
, IE,
:
/*@cc_on
@if (@_jscript)
13.7.
279
// ,
// JavaScript. IE
// , .
alert(' Internet Explorer');
@else*/
// JavaScript,
// IE.
// , IE.
alert(' Internet Explorer');
/*@end
@*/
HTML JavaScript ,
IE.
13.7.
, JavaScript
. JavaScript
: JavaScript,
.
, , , ,
.
JavaScript, ,
JavaScript . ,
JavaScript
,
. ( ,
,
, , JavaScript,
, JavaScript
.) JavaScript
, . JavaScript
, , Ja
vaScript, ( ),
JavaScript .
,
, ( )
, .
, ,
, .
,
JavaScript.
, ,
, ,
.
17, ,
280
13. JavaScript *
13.8. JavaScript
.
JavaScript.
13.8.1. JavaScript
JavaScript ,
JavaScript.
,
,
,
,
.
JavaScript ,
. , JavaScript
.
File JavaScript
.
. , JavaScript
HTTP
FTP, .
JavaScript
.
,
. ,
. ,
:
JavaScript ,
, ,
13.8. JavaScript
281
,
,
.
JavaScript
, .
self.close(),
.
JavaScript ,
, . (
,
.
.)
(
100 )
.
, .
,
; ,
, , . ,
,
,
, .
,
, .
, .
, (
, ) .
(same'origin policy)
.
13.8.2.
, JavaScript .
,
, <iframe>,
.
JavaScript
. ,
, ( ,
JavaScript ,
14.8).
282
13. JavaScript *
,
HTTP XMLHttpRequest. JavaScript
, , HTTP
, , ,
( XMLHttpRequest 20).
,
URL, . ,
, . ,
,
. , , HTTP,
, HTTPS,
.
,
:
, . ,
A ( src <script>)
B.
.
B,
.
C ( A),
.
, ,
, , Document
( . 15). ,
. (, Firefox 1.0
history.back() , IE 6 .)
, , ,
, . ,
, .
,
.
(, ,
) ,
.
.
.
. ,
. ,
home.example.com
, developer.example.com, orders.exam'
ple.com catalog.exam'
ple.com. ,
domain: Document. domain
13.8. JavaScript
283
, .
,
. , domain
"home.example.com", "examp
le.com", "home.example" "ample.com". , do
main , , ,
"com" .
( ) ,
domain,
, .
, ,
orders.example.com catalog.example.com, docu
ment.domain "example.com",
.
13.8.3.
ActiveX
JavaScript
, ,
, .
JavaScript
, ActiveX
IE .
. 20
, HTTP
ActiveX, 19 22
Java Flash.
,
ActiveX Java , ,
. Java
, , ;
.
: ,
,
. Java Flash, ,
JavaScript. ActiveX
. IE
ActiveX,
Windows
. .
13.8.4.
(cross'site scripting), XSS,
, HTML
284
13. JavaScript *
. XSS
,
. , JavaScript
, XSS .
XSS,
,
HTML.
,
JavaScript, :
<script>
var name = decodeURIComponent(window.location.search.substring(6)) || "";
document.write(" " + name);
</script>
window.location.search.substring,
,
?. document.write()
. ,
URL:
http://www.example.com/greet.html?name=
. ,
URL:
http://www.example.com/greet.html?name=%3Cscript%3Ealert('')%3C/script%3E
URL
( %3C %3E )!
,
. :
http://siteA/greet.html?name=%3Cscript src=siteB/evil.js%3E%3C/script%3E
,
. B ( C)
( ) A,
B. evil.js B,
A ,
A.
(,
, ).
A. ,
cookies, A (
),
B.
B.
XSS HTML
,
.
greet.html,
, , <script>:
13.9. JavaScript
285
,
.
,
. ,
.
CERT Advisory: http://www.cert.org/ad'
visories/CA'2000'02.html.
13.8.5.
, .
JavaScript,
alert(),
, , , kill
Unix Windows, .
.
( Firefox)
.
,
window.setInterval().
, .
. , . .
!
13.9. JavaScript
JavaScript
JavaScript, .
, ,
JavaScript:
,
HTML,
.
, .
Firefox Greasemonkey (http://greasemonkey.mozdev.org).
, , ,
.
286
13. JavaScript *
, Greasemonkey,
JavaScript
JavaScript.
SVG
SVG (Scalable Vector Graphics )
XML , JavaScript
. , JavaScript
HTML, . Ja
vaScript, SVG, XML
. , 15 17,
SVG, ,
SVG HTML.
SVG http://www.w3.org/TR/
SVG. B DOM SVG.
22 JavaScript, HTML
SVG HTML.
JavaScript SVG,
JavaScript, JavaScript, SVG.
XUL
XUL (XML User interface Language) XML
, .
Firefox
XUL. SVG, XUL Ja
vaScript. SVG, , 15
17, XUL, JavaScript XUL
, , Java
Script. XUL http://www.mozilla.org/
projects/xul http://www.xulplanet.com.
ActionScript
ActionScript , JavaScript (
ECMAScript,
) Flash
. JavaScript
ActionScript. Flash
XML, HTML,
Flash . 19, 22
23 , , Ja
vaScript Flash.
ActionScript,
JavaScript
ActionScript.
13 Window ,
JavaScript. , Window
JavaScript.
Window,
, .
, :
JavaScript
URL , ,
URL
,
, JavaScript,
JavaScript,
, ,
, . JavaScript
, , ,
. ,
288
14.
(. 15),
. , ,
, , ,
.
, ,
.
, ,
. ,
.
. ,
JavaScript
, ,
.
14.1.
. JavaScript
, JavaScript
setTimeout(), clearTimeout(), setInterval() clearIn
terval(). Win
dow, , Window
, .
setTimeout() Window
. setTimeout() ,
clearTimeout(),
.
setInterval() setTimeout(), ,
. setTimeout(),
setInterval() , clearIn
terval(), .
setTimeout() setInterval()
, JavaScript.
( )
. , IE 4,
,
JavaScript .
setTimeout() setInterval()
. ,
,
setTimeout(). ,
clearTimeout().
setTimeout() 14.7.
,
289
, setInterval(),
, .
14.4 14.6.
, setTime
out(), , 0 .
,
. setTimeout()
, , ,
.
(. 17),
(. 15), ,
,
.
, Window.
14.2.1. URL
location ( ) Location
URL ,
. href Location , URL
. toString() Location href,
location.href location.
, protocol, host, pathname search,
URL ( Location
).
search Location .
URL, ,
, . URL
. URL
URL. CGI
, , ,
, JavaScript. 14.1
getArgs(),
search URL.
14.1. URL'
/*
* URL
* name=value .
* . :
290
14.
*
* var args = getArgs(); // URL
* var q = args.q || ""; // , ,
*
//
* var n = args.n ? parseInt(args.n) : 10;
*/
function getArgs( ) {
var args = new Object();
var query = location.search.substring(1);
//
var pairs = query.split("&");
//
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
// "name=value"
if (pos == 1) continue;
//
var argname = pairs[i].substring(0,pos); //
var value = pairs[i].substring(pos+1); //
value = decodeURIComponent(value);
// ,
args[argname] = value;
//
}
return args;
//
}
14.2.2.
, location Window Location,
.
URL
URL. ,
URL location :
// Document.getElementById,
// , .
if (!document.getElementById) location = "staticpage.html";
, URL, location
, . URL
, , ,
.
14.7, ,
location.
, Window ,
.
,
URL location .
Location , .
reload() .
replace() URL.
URL
URL location . replace(), URL
URL ,
. ,
replace(),
291
,
URL location. ,
(,
), replace()
,
.
, location Window,
Location, location Document,
,
Location. document.location docu
ment.URL,
(. . ).
document.location location.href.
, document.location URL
, location.href URL.
14.2.3. History
history Window History .
History
URL.
; ,
,
, .
History .
, History .
back() forward()
( ),
. ,
. , go(),
( ) () .
back() forward() History
14.7 .
Netscape Mozilla back() forward()
Window. ,
. win
dow.back() history.back().
292
14.
14.3.1.
( Internet Explorer)
Window,
:
//
var windowWidth = window.outerWidth;
var windowHeight = window.outerHeight;
//
var windowX = window.screenX
var windowY = window.screenY
// ,
// . ,
// , ..
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
//
//
// ,
var horizontalScroll = window.pageXOffset;
var verticalScroll = window.pageYOffset;
: . ,
,
, . , ,
,
.
.
. '
HTML
.
( ),
,
.
15 16.
, Window, ,
Internet Explorer. ,
IE, <body> HTML.
, <!DOCTYPE> IE 6,
document.documentElement, document.body.
14.2.
Geometry ,
, .
14.2.
/**
* Geometry.js:
*
293
294
14.
// , .
if (document.documentElement && document.documentElement.scrollWidth) {
Geometry.getDocumentWidth =
function() { return document.documentElement.scrollWidth; };
Geometry.getDocumentHeight =
function() { return document.documentElement.scrollHeight; };
}
else if (document.body.scrollWidth) {
Geometry.getDocumentWidth =
function() { return document.body.scrollWidth; };
Geometry.getDocumentHeight =
function() { return document.body.scrollHeight; };
}
14.3.2. Screen
screen Window Screen,
.
width height . ,
, , .
availWidth availHeight ;
, ,
. Firefox ( IE) Screen
availLeft availTop.
. , ,
, (
),
.
Screen 14.4 .
14.3.3. Navigator
navigator Window Navigator,
,
. Navigator Netscape Navigator,
Internet Explorer. ( , IE
clientInformation navigator. ,
.)
Navigator
Internet Explorer Netscape.
, . .
. '
.
,
(, ).
, ,
(
17).
295
if (window.addEventListener) {
// addEventListener() , .
// ,
// Netscape, Mozilla Firefox.
}
else if (window.attachEvent) {
// , attachEvent(), .
// IE .
}
else {
// .
// , DHTML.
}
. ,
. Navigator
.
Navigator ,
:
appName
. IE "Microsoft Internet Explorer", Firefox
, Netscape (
Mozilla Netscape),
"Netscape".
appVersion
/ .
: ,
,
. , Netscape 6 Mozilla Firefox
5.0. , IE 4 6
4.0,
4 .
userAgent
, HTTP USERAGENT.
, app
Name appVersion, .
,
,
.
appCodeName
. Netscape Mozilla.
IE .
platform
, .
JavaScript 1.2.
296
14.
. 14.1. Navigator
JavaScript Navi
gator :
var browser = " :\n";
for(var propname in navigator) {
browser += propname + ": " + navigator[propname] + "\n"
}
alert(browser);
, . 14.1,
IE 6.
. 14.1, Navigator
, , . ,
appVersion.
Navigator
parseInt() String.indexOf(). 14.3 ,
Navigator
browser. ,
navigator.
(client sniffer),
. (, http://www.mozilla.org/docs/web'developer/
sniffer/browser_type.html.)
.
14.3.
/**
* browser.js:
*
* "browser",
* , "navigator".
*/
var browser = {
version: parseInt(navigator.appVersion),
isNetscape: navigator.appName.indexOf("Netscape") != 1,
14.4.
297
isMicrosoft: navigator.appName.indexOf("Microsoft") != 1
};
, :
Navigator
. , Firefox 1.0 appName "Net
scape", appVersion 5.0. Safari,
Mozilla,
! IE 6.0 appCodeName
"Mozilla", appVersion 4.0.
:
, ,
,
. , ,
.
14.4.
Window ,
. ,
,
, ,
. ,
.
14.4.1.
open() Window.
window.open() ,
, .
. open()
1,
, . JavaScript,
( )
, .
open()
Window, . open()
URL , .
( null ), .
open() . ,
target <form>
<a>. , open()
, .
1
, Mozilla
Firefox. . . .
298
14.
open() ,
.
,
, , , . .
,
. , ,
, ,
, JavaScript:
var w = window.open("smallwin.html", "smallwin",
"width=400,height=350,status=yes,resizable=yes");
: ,
.
Window.open() .
, ,
, . , ,
; ,
.
,
, open().
open() ,
.
, , URL, ,
(true)
(false). .
open() Window,
. JavaScript
, Window ,
. ? Java
Script ?
opener Window ,
. , JavaScript,
opener null.
14.4.2.
open()
close(). Window, :
w.close();
JavaScript, , :
window.close();
window
close() Window
close() Document.
, JavaScript.
14.4.
299
,
( ) .
,
.
Window
. ,
closed. true,
. , ,
, , ,
, .
14.4.3.
Window ,
. ,
,
.
, JavaScript
,
,
. ,
, ,
.
, .
moveTo()
. moveBy()
, . resizeTo() re
sizeBy() .
.
14.4.4.
focus() blur()
. focus() , blur()
. , focus() ,
, .
window.open(),
. ,
open() . open()
focus().
14.4.5.
Window ,
. scrollBy()
, , scrollTo()
. ,
300
14.
.
HTML (. 15)
, offsetLeft offsetTop, X Y
( 16.2.3 ,
).
, scrollTo() ,
.
focus()
(, ),
.
, .
: ,
, , .
: scrollIntoView() HTML
.
, , ,
, .
scrollIntoView() , focus(),
HTML, ,
. .
<a name=> ,
.
hash Location. ,
top ,
:
window.location.hash = "#top";
. ,
,
,
.
, ,
.
( )
, Location.replace():
window.location.replace("#top");
14.4.6. Window
14.4 open(), close()
moveTo() Window,
.
301
14.4.
setInterval() ,
. Screen
.
14.4.
<script>
var bounce = {
x:0, y:0, w:200, h:200, //
dx:5, dy:5,
//
interval: 100,
//
win: null,
//
timer: null,
// setInterval()
//
start: function() {
//
bounce.x = (screen.width bounce.w)/2;
bounce.y = (screen.height bounce.h)/2;
// ,
// URL javascript:
//
bounce.win = window.open('javascript:"<h1>!</h1>"', "",
"left=" + bounce.x + ",top=" + bounce.y +
",width=" + bounce.w + ",height=" +bounce.h+
",status=yes");
// setInterval() nextFrame()
// .
// ,
// clearInterval().
bounce.timer = setInterval(bounce.nextFrame, bounce.interval);
},
//
stop: function() {
clearInterval(bounce.timer);
if (!bounce.win.closed) bounce.win.close();
},
//
//
// . setInterval()
nextFrame: function() {
//
if (bounce.win.closed) {
clearInterval(bounce.timer);
return;
}
// ,
if ((bounce.x+bounce.dx > (screen.availWidth bounce.w)) ||
(bounce.x+bounce.dx < 0)) bounce.dx = bounce.dx;
// ,
if ((bounce.y+bounce.dy > (screen.availHeight bounce.h)) ||
(bounce.y+bounce.dy < 0)) bounce.dy = bounce.dy;
302
14.
//
bounce.x += bounce.dx;
bounce.y += bounce.dy;
//
bounce.win.moveTo(bounce.x,bounce.y);
//
bounce.win.defaultStatus = "(" + bounce.x + "," + bounce.y + ")";
}
}
</script>
<button onclick="bounce.start()"></button>
<button onclick="bounce.stop()"></button>
14.5.
Window
. alert() ,
. confirm()
OK .
prompt() .
,
,
. , ,
. ,
, alert(), confirm() prompt(),
. ,
, . JavaScript
alert() ,
( 15.9).
: , ,
. ,
.
JavaScript
, alert(), confirm()
prompt(). ,
, ; JavaScript ,
,
,
.
confirm() prompt() , . .
, .1
, ,
1
. . . .
14.6.
303
. 14.2. confirm()
, , ,
, .
:
,
, .
alert()
.
confirm()
14.5, , . 14.2.
14.5. confirm()
function submitQuery() {
// , .
//
// .
var message = "\n\n\n\n" +
"_________________________________________________\n\n" +
" , ,\n" +
" .\n" +
"_________________________________________________\n\n\n" +
" OK, ,\n" +
" , .";
//
// ,
if (!confirm(message)) return;
/* , */
}
14.6.
'
, .
, , ,
URL, .
, ,
status.
304
14.
, .
:
?
<a href="help.html" onmouseover="status=' !'; return true;">
</a>.
, JavaScript
onmouseover. status
true, ,
, (
URL ).
.
(, ),
status .
Window defaultStatus,
, (
, URL ).
(, Firefox 1.0 default
Status , status).
defaultStatus
. ,
, defaultSta
tus setInterval(), ,
. , .
,
setInterval(), 14.6.
14.6. ,
<script>
var WastedTime = {
start: new Date( ),
//
displayElapsedTime: function() {
var now = new Date();
//
//
var elapsed = Math.round((now WastedTime.start)/60000);
//
window.defaultStatus = " " + elapsed + " .";
}
}
//
setInterval(WastedTime.displayElapsedTime, 60000);
</script>
14.7.
onerror Window .
, ,
14.7.
305
. ( :
onerror(), . .
onerror Window. oner
ror() IE .)
.
, .
, self
myname . ,
URL JavaScript, .
, .
.
,
. JavaScript 1.5 on
error() try/catch (. 6)
.
, ,
onerror().
. oner
ror() true, ,
; ,
.
JavaScript
. , JavaScript ,
,
, . ,
, .
,
(
JavaScript, , )
, :
//
window.onerror = function() { return true; }
JavaScript
,
.
, ,
JavaScript (, Firefox),
, . ,
:
// , 3
window.onerror = function(msg, url, line) {
if (onerror.num++ < onerror.max) {
alert(": " + msg + "\n" + url + ":" + line);
return true;
}
}
306
14.
onerror.max = 3;
onerror.num = 0;
14.8.
,
.
,
,
JavaScript. ,
.1
,
, 13.8.2.
JavaScript
, ,
. ,
, . , ,
JavaScript,
,
.
,
:
, , .
, ,
, 14.7.
14.8.1.
, open() Window Window,
. ,
opener, .
,
. .
frames, parent top
Window.
JavaScript
window self.
,
window self
.
(
1
JavaScript
.
( '
, iframes),
, .
14.8.
307
), window self
.
frames.
Window, .
( , frames[] , frames.length
.) , ( )
frames[0],
frames[1] . . JavaScript, ,
:
frames[1].frames[2]
parent, Window,
. ,
( ) :
parent.frames[1]
, , parent
:
parent == self; //
,
, : parent.parent.
top:
top
. Window
, top . ,
, top parent.
<frameset> <frame>. HTML
4 <iframe>,
. JavaScript , <iframe>,
, , <frameset> <frame>. ,
, .
14.3 ,
, ,
frames, parent top.
. (, )
, .
14.8.2.
() Window.open()
. <frame>,
name .
,
target <a> <form>. ,
.
, , table_of_contents,
mainwin, table_of_contents HTML:
308
14.
. 14.3.
<a href="chapter01.html" target="mainwin"> 1. </a>
,
URL, , ,
mainwin. mainwin ,
, URL
.
target name HTML
JavaScript, JavaScript
. , Window frames[],
( ) ,
. ,
Window.
. ,
HTML:
<frame name="table_of_contents" src="toc.html">
14.8.
309
:
parent.table_of_contents
, ,
( ), :
parent.frames[1]
14.7
.
14.8.3. JavaScript
13 , Window
JavaScript,
JavaScript. :
JavaScript
. Window ,
.
, !
JavaScript, , ,
, . , ,
Window,
, , .
JavaScript
. ,
frames, parent top. , JavaScript
,
,
, .
, A i:
var i = 3;
, . .
Window. A
:
window.i
self.i
, A B,
i, A.
B i,
Window.
i :
parent.frames[0].i = 4;
310
14.
, function, ,
, var. JavaScript A
f, A.
A f :
f();
B f, Window
A:
parent.frames[0].f();
B ,
B, :
var f = parent.frames[0].f;
B f() ,
A.
,
.
, , , .
, , f
,
A, B.
, ,
. ,
<head> , ,
, , :
function debug(msg) {
alert(" : " + name + "\n" + msg);
}
JavaScript
: top.debug(). name
, ,
, .
, ,
, .
, , ,
, .
Complex, 9, HTML
:
<head>
<script src="Complex.js"></script>
</head>
<frameset rows="50%,50%">
<frame name="frame1" src="frame1.html">
<frame name="frame2" src="frame2.html">
</frameset>
14.9. :
311
:
var c = new top.Complex(3,4);
:
var Complex = top.Complex;
var c = new Complex(1,2);
,
.
,
. ,
String() String.prototype.
JavaScript
String, String.prototype ,
,
, . :
, ;
, .
14.9. :
,
, :
URL location.herf
location.
back() forward() History.
setTimeout() .
window.open().
JavaScript
.
,
.
14.7 HTML,
.
,
. ,
, URL.
. 14.4.
<script> ,
URL <form>.
. HTML
, .
312
14.
. 14.4.
14.9. :
313
// . updateURL() ,
// location.href .
setTimeout(updateURL, 1000);
}
// .
function forward() {
document.navbar.url.value = "";
try { parent.main.history.forward(); }
catch(e) {
alert(" History.forward() " +
" : "+e.message);
}
setTimeout(updateURL, 1000);
}
// back() forward()
// URL .
// location .
function updateURL() {
try { document.navbar.url.value = parent.main.location.href; }
catch(e) {
document.navbar.url.value = "< " +
" URL>";
}
}
// : URL "http://", .
function fixup(url) {
if (url.substring(0,7) != "http://") url = "http://" + url;
return url;
}
// ,
//
function go() {
// URL .
parent.main.location = fixup(document.navbar.url.value);
}
// URL,
function displayInNewWindow() {
// ,
// URL. ,
// .
window.open(fixup(document.navbar.url.value));
}
</script>
<! ,
>
<form name="navbar" onsubmit="go(); return false;">
<input type="button" value="" onclick="back();">
<input type="button" value="" onclick="forward();">
URL: <input type="text" name="url" size="50">
<input type="button" value="" onclick="go();">
<input type="button" value=" " onclick="displayInNewWindow();">
</form>
JavaScript ,
HTML .
JavaScript.
, .
( ) HTML.
Window, , document,
Document. Document
, Document.
.
, Document, ,
. HTML ,
, , . . JavaScript
, ,
. , ,
, .
(DOM)
(API), ,
. W3C DOM,
. ,
. Java
Script DOM (
).
Netscape,
.
Netscape 2 3 DOM,
, ,
. DOM
W3C DOM Level 0.
, .
15.1.
315
Internet Explorer 4
Microsoft. IE 4
,
.
, . ,
Microsoft, IE 4 DOM.
, IE 5 W3C
DOM, IE 4 DOM . IE 4 DOM
.
.
Netscape 4 DOM,
,
(layers). Netscape 4 DOM
Netscape 4.
Mozilla, Firefox , Netscape,
. Netscape 4 DOM
.
W3C DOM.
,
.
JavaScript,
. 16
W3C DOM CSS
, 17 (
, IE 4). 18
<img> HTML ,
.
DOM Level 0 Document,
Document.
W3C DOM Document,
,
HTML, XML, HTML
Document, , HTML.
, ,
W3C, HTML,
HTMLDocument.
DOM Level 0 HTML,
, HTMLDocu
ment, Document.
15.1.
Document write(),
.
DOM, JavaScript document.write()
.
316
15.
HTML ,
. , HTML
write() :
<script>
var today = new Date();
document.write("<p> : " + today.toString( ));
</script>
, HTML
.
document.write() <script>
,
. document.write()
,
! ( .)
document.write() HTML,
<script>, . <script>
defer, document.write().
defer ,
, .
,
document.write(), .
write()
JavaScript
. W3C DOM (
) ,
. document.write()
.
, write() ( open()
close() Document)
.
, ,
. ,
HTML :
// . ,
// , ,
function hello() {
var w = window.open();
//
var d = w.document;
// Document
d.open();
// ()
d.write("<h1>, !</h1>"); //
d.close();
//
}
, open()
Document, write(),
15.2. Document
317
, close() Document, ,
.
, ,
. , HTML
, close().
close(), open() .
write() , JavaScript
HTML,
write() open(). ,
document.write()
: JavaScript . (
, ) .
, : write()
.
write(). ,
, write() .
, ,
. :
document.write(", " + username + " !");
:
var greeting = ", ";
var welcome = " !";
document.write(greeting, username, welcome);
, Document writeln(),
write() ,
. ,
, <pre>.
write(), writeln(), open() close()
, HTMLDocument.
15.2. Document
Document,
:
bgColor
. bgcolor <body>.
cookie
, JavaScript
cookie. 19.
domain
, ,
,
(
. 13.8.2).
318
15.
lastModified
, .
location
URL.
referrer
URL , ( ),
.
title
<title> </title> .
URL
, URL, .
location.href Window
.
.
,
, , :
<hr><font size="1">
: <i><script>document.write(document.title);</script></i><br>
URL: <i><script>document.write(document.URL);</script></i><br>
:
<i><script>document.write(document.lastModified);</script></i>
</font>
referrer. URL ,
.
.
,
, ,
, :
<script>
// ,
//
if (document.referrer == "" || document.referrer.indexOf("mysite.com") == 1)
window.location = "http://home.mysite.com";
</script>
, .
, ,
JavaScript.
Document bgColor.
HTML, .
Java
Script .
, document.bgColor
, , "pink" "#FFAAAA".
15.3. DOM:
319
Document
, HTMLDocument.
Document ,
.
.
15.3. DOM:
Document, ,
.
, ,
.
:
anchors[]
Anchor, .
(anchor) ,
<a> href
name. name Anchor name.
Anchor .
applets[]
Applet, Java .
23.
forms[]
Form, <form> .
Form elements[],
, .
, Form on
submit.
: false,
. forms[]
DOM. 18.
images[]
Image, <img> .
src Image /. URL
(
). src Image
. 22.
links[]
Link, .
HTML <a>,
<area>.
320
15.
15.3.1.
, ,
,
, .
,
. DOM
name , ,
, .
,
. , , HTML
:
<form name="f1"><input type="button" value=" "></form>
15.3. DOM:
321
, <form> ,
JavaScript Form
:
document.forms[0]
//
document.forms.f1
// ,
document.forms["f1"] // ,
.
name , , ,
Form. ,
:
<form name="shipping">
...
<input type="text" name="zipcode">
...
</form>
:
document.shipping.zipcode
DOM. ,
name ? , , <form> <img>
n, document.n ,
.
,
name.
.
HTML
.
Form,
. 18.
15.3.2.
HTML
.
13,
.
, . .
JavaScript.
322
15.
,
17. ,
HTML, onclick onmouseover.
JavaScript,
, HTML .
, , document.links,
, HTML. Link,
, href, href <a>.
. on
click onclick <a>,
onclick Link.
onsubmit <form>. JavaScript Form
onsubmit. (, HTML
, ,
. JavaScript
.)
HTML ,
JavaScript, . JavaScript
.
<form> onsubmit:
<form name="myform" onsubmit="return validateform();">...</form>
JavaScript JavaScript,
,
:
document.myform.onsubmit = validateform;
: . ,
, .
17.
15.3.3. DOM
15.1 listanchors(),
document.write()
.
,
.
, HTML
, :
<a name="sect14.6"><h2> Anchor</h2></a>
: listanchors() Window.open().
, ,
. listanchors()
,
.
323
15.1.
/*
* listanchors.js: document.anchors[].
*
* listanchors()
* , " " .
* .
*
* .
*/
function listanchors(d) {
//
var newwin = window.open("", "navwin",
"menubar=yes,scrollbars=yes,resizable=yes," +
"width=500,height=300");
//
newwin.document.write("<h1> : " + d.title + "</h1>");
//
for(var i = 0; i < d.anchors.length; i++) {
//
// . ,
// <a> </a>, , .
// , name.
var a = d.anchors[i];
var text = null;
if (a.text) text = a.text;
// Netscape 4
else if (a.innerText) text = a.innerText;
// IE 4+
if ((text == null) || (text == '')) text = a.name; //
// . href
// :
// onclick, location.hash
// , .
// . Window.opener, Window.location,
// Location.hash Link.onclick.
newwin.document.write('<a href="#' + a.name + '"' +
' onclick="opener.location.hash=\'' + a.name +
'\'; return false;">');
newwin.document.write(text);
newwin.document.write('</a><br>');
}
newwin.document.close( ); // !
}
324
15.
15.4.1.
HTML ,
DOM .
. ,
HTML , ,
<body> <p>, , . HTML
, HTML.1
HTML:
<html>
<head>
<title>Sample Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</body>
</html>
DOM . 15.1.
,
, ,
. , ,
. 15.1. HTML'
1
DOM XML,
, HTML.
,
XML, , CDATA
. DOM XML
21.
325
. ,
,
. , ,
. ,
, . ,
, , .
15.4.2.
DOM, . 15.1,
Node . Node1
. childNodes
Node , firstChild, lastChild, next
Sibling, previousSibling parentNode .
, appendChild(), removeChild(), replaceChild() insertBefore(),
.
.
15.4.2.1.
Node. Node nodeType,
. nodeType , ,
Node.ELEMENT_NODE, , Node Element,
, Element.
. 15.1 HTML
nodeType .
15.1.
nodeType
nodeType
Element
Node.ELEMENT_NODE
Text
Node.TEXT_NODE
Document
Node.DOCUMENT_NODE
Comment
Node.COMMENT_NODE
DocumentFragment
Node.DOCUMENT_FRAGMENT_NODE
11
Attr
Node.ATTRIBUTE_NODE
DOM , . ,
,
. DOM
.
326
15.
<body>, <html>,
document.body .
DOM Document.
Element, , <html> <i>,
Text, .
, DOM
Comment. . 15.2
DOM.
15.4.2.2.
( src width <img>) ,
getAttribute(), setAttribute() removeAt
tribute() Element. , HTML
Element, .
getAttribute
Node(), Attr, .
(
Attr specified, ,
.)
Attr . 15.2 . ,
Attr childNodes[]
, Element Text. DOM
Attr attributes[] Node,
Internet Explorer attributes[],
.
327
<acronym>
<address>
<b>
<bdo>
<big>
<center>
<cite>
<code>
<dd>
<dfn>
<dt>
<em>
<i>
<kbd>
<noframes>
<noscript>
<s>
<samp>
<small>
<span>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<var>
HTML DOM,
HTML, . HTML
, ,
HTML. , <ul> HTMLU
ListElement, <body> HTMLBodyElement.
,
HTML, .
, HTMLElement, HTML,
(
).
, DOM HTML
.
getAttribute() setAttribute()
Element. ,
HTML, .
, HTML DOM,
, ,
HTML. , HTMLInputElement fo
cus() blur(), form, HTMLFormElement submit()
328
15.
15.4.3.1. HTML
HTML DOM
. ,
, HTML , Java
Script . ,
HTML, .
,
. , maxlength <input>
maxLength HTMLInputElement.
HTML JavaScript,
html. ,
for <label> htmlFor HTMLLabelElement.
class (
HTML) className
HTMLElement.1
15.4.4. DOM
, , DOM. DOM 1
(DOM Level 1) 1998 .
DOM, Node, Element, Attr Document,
, HTML. DOM 2 (DOM
Level 2) 2000 .
, DOM
(API)
(CSS),
.
DOM Level 2 . Core,
( ) Docu
ment, Node, Element Next, .
,
. DOM , ,
HTML, . . HTML. ,
CSS, Style
Sheets CSS, ( 16) CSS
1
className , . .
( HTML) ,
.
329
DHTML. ,
JavaScript ,
Events DOM.
, Events Microsoft Internet Explorer,
17, DOM,
W3C DOM IE DOM .
DOM Level 1 DOM Level 2;
IV .
W3C DOM,
3 (Level 3) ,
Core. , DOM
Level 3, ( Firefox
) .
, DOM Level 0.
,
,
Netscape Internet Explorer W3C.
DOM Level 0 DOM.
15.4.5. DOM
,
Firefox, Safari Opera, DOM Level 2.
Internet Explorer 6 DOM Level 1,
DOM Level 2. ,
Core Level 2
Events Level 2, 17. Internet
Explorer 5 5.5 ,
DOM Level 1,
.
,
,
, DOM
. ,
DOM,
.
.
implementation Document
DOMImplementation, hasFeature().
( )
( ) DOM. ,
, DOM
DOM Level 1 HTML,
:
if (document.implementation &&
document.implementation.hasFeature &&
document.implementation.hasFeature("html", "1.0")) {
330
15.
// Core HTML 1
hasFeature() :
, . true,
. . 15.3
/ , DOM Level 1 Level 2.
: ,
.
, ,
,
true. , hasFeature() ,
MouseEvents, , UIEvents,
, , Events, Views Core.
15.3. ,
hasFeature()
HTML
1.0
Core HTML 1
XML
1.0
Core XML 1
Core
2.0
Core 2
HTML
2.0
HTML 2
Core
XML
2.0
XML 2
Core
Views
2.0
AbstractView
Core
StyleSheets
2.0
Core
CSS
2.0
CSS
Core, Views
CSS2
2.0
CSS2Properties
CSS
Events
2.0
Core
UIEvents
2.0
Events, Views
( Events Views)
MouseEvents
2.0
UIEvents
HTMLEvents
2.0
HTML
Events
331
, hasFeature(), .
, IE 6 HTML 1,
. Netscape 6.1
Core Level 2,
. ,
, . ,
, .
, , ,
.
, , .
W3C (, )
DOM, http://www.w3c.org/
DOM/Test/. ,
.
,
.
http://www.quirksmode.org;
(PeterPaul Koch).
CSS DOM.
http://webdevout.net/browser_support.php;
(David Hammond).
332
15.
,
, , ,
,
, :
if (!window.Node) {
var Node = {
// Node ,
ELEMENT_NODE: 1, // .
ATTRIBUTE_NODE: 2, // , HTML
TEXT_NODE: 3,
// XML
COMMENT_NODE: 8, // .
DOCUMENT_NODE: 9,
DOCUMENT_FRAGMENT_NODE: 11
}
}
15.4.6. DOM
DOM
(API) DHTML, DOM
.
Java C++
XML .
DOM .
DOM API JavaScript,
. , ,
JavaScript get/set
. , ,
Java, getFirstChild() Node, ,
JavaScript Node API getFirstChild().
firstChild, Java
Script getFirstChild() Java.
DOM API JavaScript ,
DOM JavaScript.
item(), , ,
, .
, childNodes Node
List. Node :
, item(), ,
NodeList .
:
var
var
var
var
n = document.documentElement;
children = n.childNodes;
head = children.item(0);
body = children[1];
//
//
//
//
Node.
NodeList.
NodeList.
!
, DOM namedItem(),
,
. ,
:
333
var f = document.forms.namedItem("myform");
var g = document.forms["myform"];
var h = document.forms.myform;
NodeList , , NodeList
, , (. 7.8).
NodeList, , sort().
DOM ,
DOM API ,
API . ,
DOM .
,
.
,
. , DOM ,
,
DOM.
. ,
DOM ( ). ,
. , , Document.
, .
, , ,
Document; . . , Document,
Document. HTML
, , Document HTMLDocu
ment, , .
, CSS DOM CSS,
, Document DOM DocumentStyle Docu
mentCSS. Events Views, Document
DocumentEvent DocumentView.
, IV ,
JavaScript,
, API . ,
Document HTMLDocument,
, DocumentCSS DocumentView. ,
, Document.
, . . DOM ,
, . , ,
Text , :
var t = new Text(" "); // !
DOM ,
Document ' (factory methods)
. Text , :
var t = document.createTextNode(" ");
334
15.
, DOM, ,
create. , Document,
DOMImplementation
document.implementation.
15.5.
W3C DOM,
DOM API. ,
,
.
, DOM HTML
Node.
.
15.2. JavaScript,
HTML (. .
Element), . childNo
des . NodeList,
( JavaScript) Node.
childNodes[].
, . ,
nodeType
.
15.2.
<head>
<script>
// DOM Node. ,
// HTML, . . Element.
// , .
// Element.
// , DOM, DOM.
function countTags(n) {
// n Node
var numtags = 0;
//
if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) // , n
// Element
numtags++;
// ,
var children = n.childNodes;
// n
for(var i=0; i < children.length; i++) { //
numtags += countTags(children[i]);
//
}
return numtags;
//
}
</script>
</head>
<! countTags() >
<body onload="alert(' : ' + countTags(document))">
<i></i> .
</body>
15.6.
335
: 15.2 countTags()
onload, ,
. DOM:
,
. ( 13.5.7
. 17.7 ,
onload .)
childNodes Node
. firstChild lastChild
, nextSibling previousSibling
. ( ,
.)
, 15.3.
getText(), Text,
.
JavaScript.
DOM
.
15.3. DOM'
/**
* getText(n): Text, n.
* .
*/
function getText(n) {
// ,
// ,
// .
var strings = [];
getStrings(n, strings);
return strings.join("");
//
// .
function getStrings(n, strings) {
if (n.nodeType == 3 /* Node.TEXT_NODE */)
strings.push(n.data);
else if (n.nodeType == 1 /* Node.ELEMENT_NODE */) {
// ,
// firstChild/nextSibling
for(var m = n.firstChild; m != null; m = m.nextSibling) {
getStrings(m, strings);
}
}
}
}
15.6.
. DOM API
336
15.
. , DOM API ,
.
Document DOM,
HTML . document.docu
mentElement <html>,
. document.body <body>,
, <html>.
body Document ,
<body> HTML.
<body>
:
document.getElementsByTagName("body")[0]
getElementsByTagName()
. getElementsByTagName()
<body> . HTML
<body>, ,
.1
getElementsByTagName() HTML
. , , ,
:
var tables = document.getElementsByTagName("table");
alert(" : " + tables.length);
: HTML , ,
getElementsByTagName(), .
<table>,
<TABLE>. getElementsByTagName() ,
. , getEle
mentsByTagName() "*",
. (
IE 5 5.5. . IE Document.all[] IV
.)
,
. ,
getElementsByTagName(). ,
:
var myParagraph = document.getElementsByTagName("p")[3];
, , ( ) ,
.
1
getElementsByTagName() No
deList. NodeList
, .
15.6.
337
,
id, (
) . .
, :
<p id="specialParagraph">
JavaScript:
var myParagraph = document.getElementById("specialParagraph");
: getElementById() ,
getElementsByTagName(). id
( ) , getElementById()
id.
getElementById() DOM
.
:
// x , ,
// .
// , x ,
// .
function id(x) {
if (typeof x == "string") return document.getElementById(x);
return x;
}
DOM,
. x
x = id(x).
1,
JavaScript, ,
$().
, getElementById() getElementsByTagName(),
Document. Element getElementsByTag
Name(). Element , Document,
, ,
, . , ,
getElementById() ,
getElementsByTagName()
, :
// Table
// .
var tableOfContents = document.getElementById("TOC");
var rows = tableOfContents.getElementsByTagName("tr");
var numrows = rows.length;
1
Prototype, (Sam
Stephenson) http://prototype.conio.net.
338
15.
, , HTML HTMLDocument
getElementsByName(). getElementById(),
name, id. ,
name (
, HTML
name), getElementsByName() ,
. :
// <a name="top">
var link = document.getElementsByName("top")[0];
// <input type="radio" name="shippingMethod">
var choices = document.getElementsByName("shippingMethod");
. class HTML
className JavaScript (
).
CSS ( . 16),
. , HTML
, :
<div class="warning">
</div>
, CSS,
, ,
. , JavaScript
, <div>,
, ?
15.4. getElements(),
/ .
, className, ,
. getEle
ments() isMember(),
HTML .
15.4. HTML'
/**
* getElements(classname, tagname, root):
* DOM, ,
* root.
*
* classname ,
* .
* tagname , .
* root , document.
* root ,
* getElementsById()
*/
function getElements(classname, tagname, root) {
15.7.
339
// ,
// ,
if (!root) root = document;
else if (typeof root == "string") root = document.getElementById(root);
// ,
if (!tagname) tagname = "*";
// , root
var all = root.getElementsByTagName(tagname);
// ,
if (!classname) return all;
//
var elements = [];
//
for(var i = 0; i < all.length; i++) {
var element = all[i];
if (isMember(element, classname)) // isMember()
elements.push(element);
//
}
// : ,
return elements;
// .
// ,
// className .
// , .
function isMember(element, classname) {
var classes = element.className;
//
if (!classes) return false;
//
if (classes == classname) return true; //
// , ,
// .
var whitespace = /\s+/;
if (!whitespace.test(classes)) return false;
// ,
// , .
var c = classes.split(whitespace);
//
for(var i = 0; i < c.length; i++) {
//
if (c[i] == classname) return true; //
}
return false; //
}
}
15.7.
,
DOM API , Java
Script .
.
340
15.
15.5 . 15.3 ,
.
: 15.5
. ,
. NodeList, childNodes
getElementByTagName(), , . .
NodeList.
,
.
15.7.
341
. 15.3.
,
, .
15.5 , .
15.6 , .
upcase(),
,
.
15.6.
// n ,
// Text .
function upcase(n) {
if (n.nodeType == 3 /*Node.TEXT_NODE*/) {
// Text, .
n.data = n.data.toUpperCase( );
}
else {
// Text,
// .
var kids = n.childNodes;
for(var i = 0; i < kids.length; i++) upcase(kids[i]);
}
}
15.6 data
. , ,
Text appendData(), insertData(), de
leteData() replaceData().
Text, CharacterData.
CharacterData IV .
15.5 ,
.
, DOM API
( ). 15.7
342
15.
embolden(),
( createElement() Document),
HTML <b>,
<b>. HTML
.
15.7. <b>
<script>
// n,
// Element, HTML <b>,
// <b>.
function embolden(n) {
if (typeof n == string) n = document.getElementById(n);
//
var b = document.createElement("b"); // <b>
var parent = n.parentNode;
//
parent.replaceChild(b, n);
// <b>
b.appendChild(n);
// <b>
}
</script>
<! >
<p id="p1"><i> </i> #1.</p>
<p id="p2"><i> </i> #2.</p>
<! , embolden() (p1) >
<button onclick="embolden('p1');"> </button>
15.7.1.
, ,
,
.
element.setAttribute(). :
var headline = document.getElementById("headline"); //
headline.setAttribute("align", "center");
// align='center'
16,
CSS HTML.
,
.
15.7.2.
DocumentFragment ,
,
15.8.
343
. DocumentFragment
( appendChild(), insertBefore() replaceChild() Node),
DocumentFragment, .
DocumentFragment document.createDocumentFragment().
DocumentFragment appendChild()
, Node. ,
, DocumentFragment.
,
, .
15.8. reverse(),
DocumentFragment
.
15.8. DocmentFragment
//
function reverse(n) {
// DocumentFragment,
//
var f = document.createDocumentFragment( );
//
// .
// n
// f, .
// : f
// n.
while(n.lastChild) f.appendChild(n.lastChild);
// f n .
n.appendChild(f);
}
15.8.
Document.createElement() Document.createTextNode()
Element Text, Node.appendChild(), Node.insertBefore() Node.replace
Child() .
DOM .
15.9 log()
. ,
log.debug(), alert(),
. log()
, JavaScript.
, ,
,
.
createElement() createTextNode().
CSS (
) log() . 15.4.
344
15.
. 15.4. log()
15.9 ,
. create
Element(), createTextNode() appendChild().
HTML
log.makeTable().
15.9. JavaScript'
/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
Log.js: C
log().
:
category: . ,
, ,
.
.
message: . ,
object: . .
, .
, , .
:
15.8.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
log.debug() log.warn() ,
log() "debug"
"warning". ,
alert() log().
** .
.
<div>
id "<category>_log".
c "debug" :
<div id="debug_log"></div>
, .
. ,
"debug",
log.options.debugEnabled = true.
<div class="log">, .
id :
log.options.debugDisabled=true.
, ,
false.
CSS,
. <div> CSS
<category>_message. , "debug"
"debug_message"
Log
log.options, , , ,
/
. :
log.options.timestamp: true,
.
log.options.maxRecursion: ,
.
, 0
log.options.filter: , ,
345
346
15.
* .
* true,
* , false
*/
function log(category, message, object) {
// ,
if (log.options[category + "Disabled"]) return;
//
var id = category + "_log";
var c = document.getElementById(id);
// ,
// .
if (!c && log.options[category + "Enabled"]) {
c = document.createElement("div");
c.id = id;
c.className = "log";
document.body.appendChild(c);
}
//
if (!c) return;
// / ,
if (log.options.timestamp)
message = new Date() + ": " + (message?message:"");
// <div>,
var entry = document.createElement("div");
entry.className = category + "_message";
if (message) {
//
entry.appendChild(document.createTextNode(message));
}
if (object && typeof object == "object") {
entry.appendChild(log.makeTable(object, 0));
}
//
c.appendChild(entry);
}
//
log.makeTable = function(object, level) {
// , , Text.
if (level > log.options.maxRecursion)
return document.createTextNode(object.toString());
// ,
var table = document.createElement("table");
table.border = 1;
// ||
var header = document.createElement("tr");
var headerName = document.createElement("th");
var headerType = document.createElement("th");
15.8.
347
348
15.
}
// options
log.options = {};
//
log.debug = function(message, object) { log("debug", message, object); };
log.warn = function(message, object) { log("warning", message, object); };
// , alert()
// , log()
// function alert(msg) { log("alert", msg); }
, . 15.4,
:
<head>
<script src="Log.js"></script>
<! log() >
<link rel="stylesheet" type="text/css" href="log.css"><! >
</head>
<body>
<script>
function makeRectangle(x, y, w, h) {
//
log.debug(" makeRectangle"); //
var r = {x:x, y:y, size: { w:w, h:h }};
log.debug(" ", r); //
log.debug(" makeRectangle");
//
return r;
}
</script>
<! >
<button onclick="makeRectangle(1,2,3,4);"> </button>
<! >
<! <div> >
<div id="debug_log" class="log"></div>
</body>
. 15.4
CSS, <link>.
:
#debug_log { /* */
backgroundcolor: #aaa; /* */
border: solid black 2px; /* */
overflow: auto;
/* */
width: 75%;
/* */
height: 300px;
/* */
}
#debug_log:before { /* */
content: " ";
display: block;
textalign: center;
font: bold 18pt sansserif ;
}
.debug_message { /* */
borderbottom: solid black 1px;
}
15.8.
349
CSS 16.
. ,
CSS ,
log().
15.8.1.
15.9 ,
: ,
Element, ,
Text Element. Element
Element . . <table>,
, 15.9
13 . 15.10
Element ,
DOM
.
15.10 make().
Element ,
. ,
. ,
, Element,
make().
make()
. ;
.
, , .
,
, .
make() 13 ,
15.9 <table>, :
var table = make("table", {border:1}, make("tr", [make("th", ""),
make("th", ""),
make("th", "")]));
. 15.10
make() maker().
,
make() .
,
:
var table = maker("table"), tr = maker("tr"), th = maker("th");
:
var mytable = table({border:1}, tr([th(""), th(""), th("")]));
350
15.
15.10.
/**
* make(tagname, attributes, children):
* HTML tagname,
* .
*
* attributes JavaScript:
* . , children
* , attributes
* , children .
*
* , children
* , .
* , children .
* , ,
* . (
* , .)
*
* : make("p", [" ", make("b", ""), " ."]);
*
* MochiKit (http://mochikit.com),
* (Bob Ippolito)
*/
function make(tagname, attributes, children) {
// attributes
// , , children.
if (arguments.length == 2 &&
(attributes instanceof Array || typeof attributes == "string")) {
children = attributes;
attributes = null;
}
//
var e = document.createElement(tagname);
//
if (attributes) {
for(var name in attributes) e.setAttribute(name, attributes[name]);
}
// , .
if (children != null) {
if (children instanceof Array) {
//
for(var i = 0; i < children.length; i++) { //
var child = children[i];
if (typeof child == "string")
//
child = document.createTextNode(child);
e.appendChild(child);
// Node
}
}
else if (typeof children == "string") // Text
e.appendChild(document.createTextNode(children));
else e.appendChild(children);
//
}
15.9. :
351
//
return e;
}
/**
* maker(tagname): , make() .
* : var table = maker("table"), tr = maker("tr"), td = maker("td");
*/
function maker(tag) {
return function(attrs, kids) {
if (arguments.length == 1) return make(tag, attrs);
else return make(tag, attrs, kids);
}
}
15.8.2. innerHTML
W3C innerHTML
DOM, HTMLElement
, .
HTML ,
.
HTML
, .
HTML HTML
,
createElement() appendChild(). 15.9,
<table> .
innerHTML
:
var table = document.createElement("table"); // <table>
table.border = 1;
//
// ||
table.innerHTML = "<tr><th></th><th></th><th></th></tr>";
HTML.
, innerHTML ,
HTML. ,
innerHTML
+= ,
, .
innerHML Microsoft IE 4.
. , outer
HTML, innerText outerText, ,
Firefox .
15.9. :
, Core
DOM API , ,
352
15.
.
15.11, HTML.
maketoc()
onload,
. maketoc()
<h1>, <h2>, <h3>, <h4>, <h5> <h6>, , ,
. , maketoc()
id="toc"
. maketoc()
,
. ,
maketoc(), . 15.5.
maketoc() ,
, <h1>, <h2>
. ,
,
. 15.11
: ,
HTML maketoc(),
. CSS
. :
. 15.5.
15.9. :
353
TOC.js. 15.11
, .
W3C DOM.
15.11.
/**
* TOC.js: .
*
* maketoc(),
* onload,
*
* maketoc()
* id="toc".
* , maketoc() . ,
* maketoc() , <h1> <h6>
* , "toc".
* maketoc()
*
* , "TOC",
* maketoc(), ..
* HTML.
*
* CSS.
* "TOCEntry". ,
* , .
* <h1> "TOCLevel1",
* <h2> "TOCLevel2", ..
* , "TOCSectNum",
* ,
* "TOCBackLink".
354
15.
*
* "Contents".
* (, ),
* maketoc.backlinkText.
**/
function maketoc() {
// . .
var container = document.getElementById('toc');
if (!container) return;
// , <h1>...<h6>
var sections = [];
findSections(document, sections);
// ,
//
var anchor = document.createElement("a"); // <a>
anchor.name = "TOCtop";
//
anchor.id = "TOCtop";
// name id ( IE)
container.parentNode.insertBefore(anchor, container); //
//
var sectionNumbers = [0,0,0,0,0,0];
//
for(var s = 0; s < sections.length; s++) {
var section = sections[s];
//
var level = parseInt(section.tagName.charAt(1));
if (isNaN(level) || level < 1 || level > 6) continue;
//
//
sectionNumbers[level1]++;
for(var i = level; i < 6; i++) sectionNumbers[i] = 0;
// ,
// , , , 2.3.1
var sectionNumber = "";
for(i = 0; i < level; i++) {
sectionNumber += sectionNumbers[i];
if (i < level1) sectionNumber += ".";
}
// .
// <span>, .
var frag = document.createDocumentFragment(); //
var span = document.createElement("span");
// span
span.className = "TOCSectNum";
//
span.appendChild(document.createTextNode(sectionNumber)); //
frag.appendChild(span);
//
frag.appendChild(document.createTextNode(" ")); //
section.insertBefore(frag, section.firstChild); //
// , .
var anchor = document.createElement("a");
anchor.name = "TOC"+sectionNumber;
// ,
15.9. :
355
anchor.id = "TOC"+sectionNumber; // IE
// id
//
var link = document.createElement("a");
link.href = "#TOCtop";
link.className = "TOCBackLink";
link.appendChild(document.createTextNode(maketoc.backlinkText));
anchor.appendChild(link);
//
section.parentNode.insertBefore(anchor, section);
// .
var link = document.createElement("a");
link.href = "#TOC" + sectionNumber; //
link.innerHTML = section.innerHTML; //
// div,
//
var entry = document.createElement("div");
entry.className = "TOCEntry TOCLevel" + level; // CSS
entry.appendChild(link);
// div
container.appendChild(entry);
}
// n,
// <h1> <h6> .
function findSections(n, sects) {
// n
for(var m = n.firstChild; m != null; m = m.nextSibling) {
// , .
if (m.nodeType != 1 /* Node.Element_NODE */) continue;
// ,
if (m == container) continue;
// <p>,
// ,
// . ( , ,
// <pre> , <p> .)
if (m.tagName == "P") continue; //
//
//
//
//
//
//
if
, .
, .
.
: DOM ,
,
(m instanceof HTMLHeadingElement).
(m.tagName.length==2 && m.tagName.charAt(0)=="H")
sects.push(m);
else
findSections(m, sects);
}
}
}
//
356
15.
maketoc.backlinkText = "Contents";
// maketoc() onload
if (window.addEventListener) window.addEventListener("load", maketoc, false);
else if (window.attachEvent) window.attachEvent("onload", maketoc);
15.10.
,
. ,
. 15.12 , .
15.12.
function getSelectedText() {
if (window.getSelection) {
// , , .
// getSelection() Selection,
// .
return window.getSelection().toString();
}
else if (document.getSelection) {
// ,
return document.getSelection( );
}
else if (document.selection) {
// IE.
// selection, TextRange, IE.
return document.selection.createRange().text;
}
}
. Selec
tion TextRange, , .
(API)
.
,
. , ,
(. 13.4.1),
. , HTML
(Wikipedia).
URL javascript:,
:
<a href="javascript:
var q;
if (window.getSelection) q = window.getSelection().toString();
else if (document.getSelection) q = document.getSelection();
else if (document.selection) q = document.selection.createRange().text;
void window.open('http://en.wikipedia.org/wiki/' + q);
">
Wikipedia
</a>
15.11. IE 4 DOM
357
15.11. IE 4 DOM
IE 4 W3C DOM, API
, W3C DOM. IE 5
IE 4 DOM, ,
, .
IE 4 . Java
Script , , IE 4,
IE 4 DOM
. ,
IE 4 DOM, ,
.
15.11.1.
W3C DOM , Node, Docu
ment Element, childNodes[],
. IE 4 childNodes[],
children[] Document HTMLElement.
HTML IE 4
, 15.2.
children[] IE 4 childNo
des[] W3C DOM . IE 4 Text,
. ,
<p>, , IE 4
children[]. , <p>
IE 4 innerText.
15.11.2.
IE 4 getElementById() getElementsByTagName()
Document. Document
358
15.
all[]. ,
(all) , .
, all[]
.
all[] .
n, n+1
. :
var e1 = document.all[0]; //
var e2 = e1.all[4];
// 1
. API IE 4
DOM: IE , all[]
, .
, . getElementById()
IE 4 all[] , .
, IE 4 ,
id name .
( , . . ,
, name),
. :
var specialParagraph = document.all["special"];
var radioboxes = form.all["shippingMethod"]; //
JavaScript ,
:
var specialParagraph = document.all.special;
var radioboxes = form.all.shippingMethod;
all[]
, getElementById() getElementsByName().
, all[] ,
id name .
all[] tags(),
:
var lists = document.all.tags("UL"); // <ul>
var items = lists[0].all.tags("LI"); // <li> <ul>
IE 4 ,
getElementsByTagName() Document Element DOM.
, IE 4 .
15.11. IE 4 DOM
359
15.11.3.
W3C DOM, IE 4 HTML
HTMLElement.
, IE 4, HTML.
,
, .
HTMLElement IE 4 setAttribute(), getAttribute()
removeAttribute(). ,
Element DOM.
W3C DOM ,
, ,
. IE 4 .
HTMLElement IE 4 innerHTML.
HTML
. innerHTML
,
DOM. innerHTML
15.8.2.
IE 4 . outerHTML
HTML
. innerText outerText innerHTML outerHTML
,
HTML. , insertAdjacentHTML() insertAdja
centText() ,
HTML ( , )
. , in
nerHTML, Firefox.
CSS DHTML
(Cascading Style Sheets, CSS)
HTML XML.
HTML,
HTML, <font>,
CSS, ,
. , CSS ,
, <h1>,
, sansserif 24 ,
.
CSS , ,
HTML.
, JavaScript, . .
. CSS JavaScript
,
HTML (Dynamic HTML, DHTML).1
CSS
, . , CSS
. , DHTML
, , ,
,
.
CSS. ,
CSS .
CSS .
1
DHTML
, 17.
16.1. CSS
361
style . ,
CSS
, .
className.
.
, ,
.
16.1. CSS
CSS
, .
. ,
:
fontweight: bold; color: blue; textdecoration: underline;
CSS . . 16.1
, ,
. ,
. CSS
,
. CSS
OReilly Cascading Style Sheets: The Definitive Guide1
(Eric Meyer) Dynamic HTML: The Definitive Guide
(Danny Goodman). http://
www.w3c.org/TR/CSS21/.
. 16.1
. , CSS.
, ,
, . ,
, , string ()
length (). , length ,
, px ().
CSS. , ,
, CSS.
, ,
inherit, ,
.
, |,
. , ||,
,
( ). []
. * ,
, + ,
1
CSS . , 3
. . . .: , 2008.
362
,
? ,
.
. , {2}
, {1,4}
. (
,
JavaScript, 11.)
16.1. CSS'
background
color | transparent
backgroundimage
backgroundposition
backgroundrepeat
border
bordercollapse
collapse | separate
bordercolor
color{1,4} | transparent
borderspacing
length length?
borderstyle
bordertop
borderright
borderbottom
borderleft
bordertopcolor
borderrightcolor
borderbottomcolor
borderleftcolor
color | transparent
bordertopstyle
borderrightstyle
borderbottomstyle
borderleftstyle
bordertopwidth
borderrightwidth
borderbottomwidth
borderleftwidth
363
16.1. CSS
borderwidth
bottom
captionside
top | bottom
clear
clip
color
color
content
counterincrement
counterreset
cursor
direction
ltr | rtl
display
emptycells
show | hide
float
font
fontfamily
fontsize
fontstyle
fontvariant
normal | smallcaps
fontweight
normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700
| 800 | 900
height
left
letterspacing
normal | length
lineheight
liststyle
liststyleimage
url(url) | none
364
16.1 ()
liststyleposition
inside | outside
liststyletype
margin
margintop
marginright
marginbottom
marginleft
markeroffset
length | auto
maxheight
maxwidth
minheight
length | percentage
minwidth
length | percentage
outline
outlinecolor
color | invert
outlinestyle
outlinewidth
overflow
padding
[length | percentage]{1,4}
paddingtop
paddingright
paddingbottom
paddingleft
length | percentage
pagebreakafter
pagebreakbefore
pagebreakinside
avoid | auto
position
quotes
right
tablelayout
auto | fixed
textalign
textdecoration
365
16.1. CSS
textindent
length | percentage
texttransform
top
unicodebidi
verticalalign
visibility
whitespace
width
wordspacing
normal | length
zindex
auto | integer
CSS ,
, .
, fontfamily, fontsize, fontstyle fontweight
font:
font: bold italic 24pt helvetica;
margin padding , ,
. mar
gin marginleft, marginright, margintop marginbottom.
padding.
16.1.1.
.
, style HTML.
, :
<p style="marginleft: 1in; marginright: 1in;">
CSS
. style
HTML (
DHTML).
, (stylesheets),
. CSS
. ,
, ;
,
.
. , ,
<body>:
body { marginleft: 30px; marginright: 15px; backgroundcolor: #ffffff }
366
, <h1> <h2>
:
h1, h2 { textalign: center; }
, . ,
, ,
. , , <block
quote> , <i>,
<blockquote>, :
blockquote { fontstyle: italic; }
blockquote i { fontstyle: normal; }
,
, .
class HTML. , ,
class="attention"
:
.attention { fontweight: bold; }
.
, <p> class="attention",
( ,
):
p.attention { color: red; }
, ,
, id.
, id, p1, :
#p1 { visibility: hidden; }
id : DOM getElement
ById() .
,
.
visibility hidden ()
visible (), .
, .
CSS , ,
,
.
CSS .
16.1.2.
HTML,
<style> </style> , ,
HTML <link>. :
16.1. CSS
367
<html>
<head><title> </title>
<style type="text/css">
body { marginleft: 30px; marginright: 15px; backgroundcolor: #ffffff }
p { fontsize: 24px; }
</style>
</head>
<body><p>, </p></body>
</html>
,
HTML.
CSS HTML.
<script>, <style> src. ,
HTML, <link>:
<html>
<head><title> </title>
<link rel="stylesheet" href="mystyles.css" type="text/css">
</head>
<body><p>, </p></body>
</html>
<link> .
( Firefox)
( > ). ,
,
:
<link rel="alternate stylesheet" href="largetype.css" type="text/css"
title=" "> <! >
<style>
, CSS,
CSS @import:
<html>
<head><title> </title>
<style type="text/css">
@import "mystyles.css"; /* */
p { fontsize: 48px; } /* */
</style>
</head>
<body><p>, </p></body>
</html>
16.1.3.
, C CSS cascade ().
, ,
, .
, ,
HTML,
.
368
<style>
, .
HTML style.
CSS , ,
. ,
,
, ,
,
. ,
, !important,
.
, ,
, ,
. , id ,
. , class, .
, , , ,
, , ,
.
16.1.4. CSS
CSS . 1996
CSS1 , , ,
. , Netscape 4 Internet Explorer 4,
CSS1, , . ,
CSS2, 1998 ;
, .
,
CSS2, .
CSS2 CSSPosition
ing (CSSP), DHTML
. (
.)
CSS .
CSS2.1 .
CSS2, , ,
. CSS
, .
CSS3 ,
CSS3, opacity. CSS
http://www.w3.org/Style/CSS/.
16.1.5. CSS
16.1 HTML,
. ,
16.1. CSS
369
, ,
, style. . 16.1 ,
. ,
CSS.
CSS .
16.1.
<head>
<style type="text/css">
/* , . */
h1, h2 { color: blue; fontstyle: italic }
/*
* class="WARNING"
* , .
*/
.WARNING {
fontweight: bold;
fontsize: 150%;
margin: 0 1in 0 1in; /* , */
backgroundcolor: yellow;
border: solid red 8px;
padding: 10px; /* 10 4 */
}
/*
* h1 h2 class="WARNING"
* , .
*/
.WARNING h1, .WARNING h2 { textalign: center }
/* id="P23" .
*/
370
#P23 {
textalign: center;
texttransform: uppercase;
}
</style>
</head>
<body>
<h1> </h1>
<div class="WARNING">
<h2></h2>
!
,
. ,
.
</div>
<p id="P23">
<br>
.<br>
<span style="texttransform: none">
.
</span>
</p>
</body>
position
top, left
bottom, right
width, height
zindex
( )
display
visibility
clip
(
, )
371
()
overflow
, ,
,
opacity
( ) .
CSS3
. IE
16.2.1. DHTML:
CSS position , .
:
static
, . ,
(
). DHTML
top, left
.
DHTML position
.
absolute
.
.
, ,
, .
DHTML . IE 4
.
,
<div> <span>.
fixed
.
. ,
.
, IE 6.
relative
position relative,
,
372
. ,
,
, , ,
.
position , static,
left, top, right bottom.
left top,
( )
. ,
100 100
, CSS style
:
<div style="position: absolute; left: 100px; top: 100px;">
,
, ,
.
,
,
.
( <body>).
, .
.
, ,
position:relative ,
top left 0px.
.
.
left top, right bottom
. , ,
(, ):
position: absolute; right: 0px; bottom: 0px;
10
, 10 ,
:
position: absolute; right: 10px; top: 10px;
CSS .
width height. ,
HTML
373
left right. ,
, top bottom. left, right
width, width right,
, height bottom.
,
. , ,
. , ,
,
.
px, pixels (). CSS
,
(in), (cm), (pt)
(em). DHTML
. , CSS
.
, ,
.
CSS
. HTML ,
(
) :
<div style="position: absolute; left: 25%; top: 25%; width: 50%; height: 50%;
border: 2px solid black">
</div>
16.2.2. CSS:
CSS2 textshadow,
.
Safari,
. CSS2.1, CSS3
.
textshadow. CSS
:
, ( )
( ).
(. 16.2):
374
. 16.2. ,
CSS'
<div style="font: bold 32pt sansserif;"> <! >
<! , >
<! >
<! >
<span style="position:relative;">
<! >
<! >
<! >
<span style="position:absolute; top:5px; left:5px; color: #ccc"> </span>
<span style="position:absolute; top:3px; left:3px; color: #888"> </span>
<span style="position:absolute; top:1px; left:1px; color: #444"> </span>
<! , . >
<! , >
<! >
<span style="position:relative"> </span>
</span>
| <! >
</div>
,
. JavaScript.
16.2 JavaScript Shadows.js.
Shadows.addAll(), ( )
shadow.
shadow DOM API ,
, .
, . 16.2:
<head><script src="Shadows.js"></script></head> <! >
<body onload="Shadows.addAll( );"> <! >
<div style="font: bold 32pt sansserif;"> <! >
<! shadow >
<span shadow='5px 5px #ccc 3px 3px #888 1px 1px #444'> </span> |
</div>
</body>
Shadows.js. ,
DOM,
CSS. CSS
, CSS
375
.
CSS.
16.2. JavaScript'
/**
* Shadows.js: CSS.
*
* Shadows.
* .
*
* Shadows.add(element, shadows):
* .
* .
* .
* .
* shadows .
*
* Shadows.addAll(root, tagname):
*
* .
* shadow, Shadows.add(),
* shadow. ,
* . ,
* . .
*
*
*
* [x y color]+. ,
* x, y .
* CSS.
* ,
* . : "4px 4px #ccc 2px 2px #aaa"
*/
var Shadows = {};
//
Shadows.add = function(element, shadows) {
if (typeof element == "string")
element = document.getElementById(element);
// ,
//
shadows = shadows.replace(/^\s+/, "").replace(/\s+$/, "");
var args = shadows.split(/\s+/);
// , .
// ,
// .
// .
var textnode = element.firstChild;
// ,
// .
// .
element.style.position = "relative";
376
//
var numshadows = args.length/3;
for(var i = 0; i < numshadows; i++) {
var shadowX = args[i*3];
var shadowY = args[i*3 + 1];
var shadowColor = args[i*3 + 2];
//
//
//
//
//
?
X
Y
// <span>
var shadow = document.createElement("span");
// style
shadow.setAttribute("style", "position:absolute; " +
"left:" + shadowX + "; " +
"top:" + shadowY + "; " +
"color:" + shadowColor + ";");
// span
shadow.appendChild(textnode.cloneNode(false));
// span
element.appendChild(shadow);
}
// . <span>
var text = document.createElement("span");
text.setAttribute("style", "position: relative"); //
text.appendChild(textnode); //
element.appendChild(text); // span
};
// , ,
// .
// shadow, Shadows.add()
// . root , document.
// , .
Shadows.addAll = function(root, tagname) {
if (!root) root = document; // ,
//
if (!tagname) tagname = '*'; // ,
var elements = root.getElementsByTagName(tagname); //
for(var i = 0; i < elements.length; i++) {
//
var shadow = elements[i].getAttribute("shadow"); // ,
if (shadow) Shadows.add(elements[i], shadow);
//
}
};
16.2.3.
, , CSS HTML
, :
? ,
CSS DHTML HTML,
.
X Y
offsetLeft offsetTop.
377
offsetWidth offsetHeight.
( CSS px). CSS left, top,
width height, CSS. ,
: Microsoft IE 4
.
, offsetLeft offsetTop .
X Y
, offsetParent.
offsetParent <body> <html>
( offsetParent null)
.
offsetParent . ,
IE .
,
, offsetParent
. ,
:
// e X.
function getX(e) {
var x = 0;
// 0
while(e) {
// e
x += e.offsetLeft; //
e = e.offsetParent; // offsetParent
}
return x;
//
}
getY() offsetLeft
offsetTop.
, , getX(),
. CSS
. 17
, , ,
,
.
getX() .
, CSS overflow
.
,
.
, ,
:
function getY(element) {
var y = 0;
for(var e = element; e; e = e.offsetParent) // offsetParent
y += e.offsetTop;
// offsetTop
// , ,
378
16.2.4. : zindex
, left, top, right bottom
X Y .
zindex
, ,
. zindex
. ,
. ,
zin
dex, . . zindex .
zindex,
, ,
.
: zindex
(. . ).
,
zindex , .
zindex
.
(. .
position:static) ,
, zindex .
zindex , . .
zindex
,
zindex .
, , z
index, <iframe>,
,
.
, <select>.
zindex.
16.2.5.
CSS:
visibility display. visibility : hidden,
379
, visible, . display
, ,
, , .
display none,
.
visibility display
, . ,
( position,
static relative), visibility hidden
, .
. display none,
;
, . (
visibility display
, . .
.) visibility
, display
.
: visibility dis
play, ,
JavaScript,
! , .
16.2.6. CSS
CSS , ,
CSS,
,
width, height, top left . (box
model) CSS (. 16.3).
.
border, margin padding.
, ( )
. CSS , :
border: solid black 1px; /*
/*
border: 3px dotted red; /*
/*
,
1 */
*/
3 */
,
CSS,
. , ,
borderbottom. ,
. . 16.3,
, bordertopwidth borderleftwidth.
margin padding
. ( ) ,
380
. 16.3. CSS (, )
margin ,
, padding ,
. margin
( )
. padding
. ,
padding .
, ,
margin. (
. 16.3 margin .)
margin padding
:
margin: 5px; padding: 5px;
:
marginleft: 25px;
paddingbottom: 5px;
margin padding
.
, . .
: , , , . ,
:
padding: 1px 2px 3px 4px;
/* . */
paddingtop: 1px;
paddingright: 2px;
381
paddingbottom: 3px;
paddingleft: 4px;
margin .
, , ,
CSS. ,
width height
, ,
.
, ,
,
. , ,
, ,
.
width height
, , left top (
right bottom)
. . CSS ,
(. . ).
. 16.3, ,
. ,
, 10
, 5 . ,
.
left 0px, ,
.
, ,
(. . ).
,
left top 10px.
382
HTML 4.0 ( )
XHTML. ,
HTML IE 6
:
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.0//EN">
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.0 Strict//EN">
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
(
) Internet Explorer.
<!DOCTYPE>,
,
, .
, IE .
16.2.7. ,
,
,
red () black ().
CSS ,
, .
. :
#000000
#fff
#f00
#404080
#ccc
/*
/*
/*
/*
/*
*/
*/
*/
*/
*/
,
CSS color.
,
backgroundcolor. CSS ,
, ,
(
) .
22,
DOM API CSS.
backgroundcolor
. backgroundimage
, backgroundattachment, backgroundposi
tion backgroundrepeat
. background,
.
,
.
, ,
. ,
383
<div>
,
<div>. <div> ,
, .
. ,
, , <button>, .
back
groundcolor, ,
.
, , ,
: , .
(
, );
. 16.4. opacity CSS3.
0 1, 1 100
( ), 0 100
. opacity Firefox.
Mozilla
mozopacity. IE
filter. 75%,
CSS:
opacity: .75;
/* CSS3 */
mozopacity: .75;
/* Mozilla */
filter: alpha(opacity=75); /* IE; */
/* */
384
auto
,
.
overflow , ,
, clip
,
, .
DHTML,
.
clip . CSS2
, clip
,
. clip:
rect(top right bottom left)
,
, px
. .
,
, .
auto ,
. , 100
style:
style="clip: rect(auto 100px auto auto);"
, ,
, .
16.2.9. :
,
CSS. 16.3 CSS
, .
. 16.4. JavaScript
, (
), ,
CSS.
16.3. CSS'
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.0//EN">
<head>
<style type="text/css">
385
. 16.4. , CSS
/**
* CSS ,
* "".
* .
*
* .
**/
div.window {
/* */
position: absolute;
/* */
width: 300px; height: 200px; /* */
border: 3px outset gray;
/* 3D */
}
div.titlebar {
/* , */
position: absolute;
/* */
top: 0px; height: 18px;
/* 18px + */
width: 290px;
/* 290 + 5px = 300 */
backgroundcolor: #aaa;
/* */
borderbottom: groove gray 2px; /* */
padding: 3px 5px 2px 5px;
/* :
/* , , , */
font: bold 11pt sansserif; /* */
}
div.content { /* , */
position: absolute;
/* */
top: 25px;
/* 18px +2px +3px+2px */
height: 165px;
/* 200px 25px 10px */
width: 290px;
/* 300px 10px */
padding: 5px;
/* */
overflow: auto;
/* */
/* */
backgroundcolor: #ffffff;/* */
386
}
div.translucent {
/*
opacity: .75;
/*
mozopacity: .75;
/*
filter: alpha(opacity=75);/*
}
</style>
</head>
*/
*/
Mozilla */
IE */
<body>
<! : div "" div >
<! , . , >
<! style, >
<div class="window" style="left: 10px; top: 10px; zindex: 10;">
<div class="titlebar"> </div>
<div class="content">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br><! >
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br><! >
</div>
</div>
<! , >
<div class="window" style="left: 75px; top: 110px; zindex: 20;">
<div class="titlebar"> </div>
<div class="content translucent"
style="backgroundcolor:#d0d0d0; fontweight:bold;">
. <tt>zindex</tt>
. CSS
, .
</div>
</div>
</body>
,
.
,
,
. HTML,
,
. .
16.3.
DHTML ,
, JavaScript.
DOM Level 2 (API),
. 15 DOM API
, . ,
, style
, CSS2Properties
. JavaScript ,
387
16.3.
CSS1 CSS2. ,
style .
CSS, , ,
style . CSS2Properties
.
, CSS2Properties style
.
CSS2Properties
. ,
, .
. <img>
,
( ) . ,
style.visibility CSS visibility
hidden, :
var imgs = document.getElementsByTagName("img");
for(var i = 0; i < imgs.length; i++) {
var img=imgs[i];
if (img.width == 468 && img.height == 60)
img.style.visibility = "hidden";
}
//
//
// 468x60...
// !
,
URL javascript:
(. 13.4.1).
, CSS2Properties
CSS. CSS ,
CSS2Properties
, .
, borderleftwidth borderLeftWidth,
fontfamily :
element.style.fontFamily = "sansserif";
CSS
CSS2Properties JavaScript. float Java
, JavaScript,
. CSS2Properties
float, CSS float.
css float,
cssFloat. , float
cssFloat, CSS2Properties.
388
16.3.2.
CSS2Properties ,
. style
:
position: absolute; fontfamily: sansserif; backgroundcolor: #ffffff;
e JavaScript,
:
e.style.position = "absolute";
e.style.fontFamily = "sansserif";
e.style.backgroundColor = "#ffffff";
, .
, JavaScript. ,
CSS, ,
JavaScript.
, ,
. ,
left :
e.style.left = 300; // : ,
e.style.left = "300"; // :
JavaScript
, .
left e
300 :
e.style.left = "300px";
left ,
:
e.style.left = (x0 + left_margin + left_border + left_padding) + "px";
,
.
CSS2Properties
CSS, style ,
, JavaScript.
, , ,
, , (
, e )
, , , :
var totalMarginWidth = e.style.marginLeft + e.style.marginRight;
:
var totalMarginWidth = parseInt(e.style.marginLeft) +
parseInt(e.style.marginRight);
,
. , marginLeft mar
16.3.
389
ginRight .
, ,
, ,
.
, CSS, margin,
, margintop, marginright, marginbottom
marginleft. CSS2Properties ,
. , margin :
e.style.margin = topMargin + "px " + rightMargin + "px " +
bottomMargin + "px " + leftMargin + "px";
,
:
e.style.marginTop = topMargin + "px";
e.style.marginRight = rightMargin + "px";
e.style.marginBottom = bottomMargin + "px";
e.style.marginLeft = leftMargin + "px";
,
,
. , ,
.
, ,
CSS2Properties style HTMLElement,
.
, CSS
style
CSS
.
DHTML JavaScript.
CSS2Properties,
, JavaScript
HTML, ,
style, . ,
, 30
, leftMargin ,
, style,
, .
, CSS2Properties
, ,
CSS ,
. 16.4 getComputedStyle()
IE currentStyle, .
16.3.3. : CSS
16.4 JavaScript,
DHTML, . 16.5.
390
. 16.5. , CSS
<div>.
<div> ,
. <div>
<div>
.
. , ,
, , . ,
( position:absolute),
<div> Tooltip(). , top, left visibi
lity, Tooltip.show().
: 16.4 ,
.
,
(. 17.3).
16.4. CSS
/**
* Tooltip.js: , .
*
* Tooltip. Tooltip
* Tooltip().
* show(). ,
* hide().
*
* :
* CSS
* :
*
* .tooltipShadow {
*
background: url(shadow.png); /* * /
* }
*
* .tooltipContent {
*
left: 4px; top: 4px;
/* * /
*
backgroundcolor: #ff0;
/* * /
*
border: solid black 1px;
/* * /
391
16.3.
*
padding: 5px;
/* * /
*
font: bold 10pt sansserif; /* * /
* }
*
* ,
* PNG,
* .
* GIF.
*/
function Tooltip( ) { // Tooltip
this.tooltip = document.createElement("div"); // div
this.tooltip.style.position = "absolute";
//
this.tooltip.style.visibility = "hidden";
//
this.tooltip.className = "tooltipShadow";
//
this.content = document.createElement("div"); // div
this.content.style.position = "relative";
//
this.content.className = "tooltipContent";
//
this.tooltip.appendChild(this.content);
//
}
// ,
Tooltip.prototype.show = function(text, x, y) {
this.content.innerHTML = text;
//
this.tooltip.style.left = x + "px";
//
this.tooltip.style.top = y + "px";
this.tooltip.style.visibility = "visible"; //
.
.
.
// ,
if (this.tooltip.parentNode != document.body)
document.body.appendChild(this.tooltip);
};
//
Tooltip.prototype.hide = function() {
this.tooltip.style.visibility = "hidden"; // .
};
16.3.4. DHTML
DHTML,
JavaScript CSS, . DHTML
. , ,
, style.left
, .
style.clip
.
16.5 HTML,
div, , 500
. ,
CSS. ,
setInterval() Window.
392
16.5 .
CSS
( top, left clip).
, 16.5, . ,
,
,
16.5.
16.6 JavaScript,
CSS, .
16.6. CSS
/**
* AnimateCSS.js:
* animateCSS(),
* CSS. :
*
*
element: HTML.
*
numFrames: .
*
timePerFrame: .
*
animation: , ; .
*
whendone: , .
*
,
*
element.
*
* animateCSS() .
* animation.
* , CSS.
* , .
* ,
16.3.
393
* ,
* , .
* , ,
* , animateCSS :
*
* animateCSS(image, 25, 50, // 25
*
// 50
*
{ // top left :
*
top: function(frame,time) { return frame*8 + "px"; },
*
left: function(frame,time) { return frame*8 + "px"; }
*
});
*
**/
function animateCSS(element, numFrames, timePerFrame, animation, whendone) {
var frame = 0; //
var time = 0; // ,
// displayNextFrame() timePerFrame .
// .
var intervalId = setInterval(displayNextFrame, timePerFrame);
// animateCSS() , ,
// .
function displayNextFrame() {
if (frame >= numFrames) {
// ,
clearInterval(intervalId); //
if (whendone) whendone(element); // whendone
return;
//
}
// ,
for(var cssprop in animation) {
// ,
// .
//
// .
// try/catch, ,
// .
try {
element.style[cssprop] = animation[cssprop](frame, time);
} catch(e) {}
}
frame++;
//
time += timePerFrame; //
}
}
animateCSS(), ,
. HTMLElement.
,
.
JavaScript, .
,
.
394
animateCSS().
JavaScript , CSS,
,
.
,
. ,
,
.
16.6 ; ,
, animateCSS().
animateCSS() displayNext
Frame() , setInterval()
displayNextFrame(). displayNextFrame()
.
: displayNextFrame()
animateCSS(), ani
mateCSS(), , displayNextFrame()
animateCSS()! ( , ,
8.8.)
animateCSS(). ,
.
// "title", 40
// 50
animateCSS(document.getElementById("title"), 40, 50,
{ // top clip :
top: function(f,t) { return 300f*5 + "px"; }
clip: function(f,t) {return "rect(auto "+f*10+"px auto auto)";},
});
animateCSS()
Button .
, . ,
,
:
// ,
animateCSS(document.forms[0].elements[0], 40, 50, // , 40 , 50
{ // 100
// (200,200):
left: function(f,t){ return 200 + 100*Math.cos(f/8) + "px"},
top: function(f,t){ return 200 + 100*Math.sin(f/8) + "px"}
},
function(button) { button.value = ""; });
JavaScript Scriptaculos
. ,
http://script.aculo.us/.
16.4.
395
16.4.
style HTML HTML style,
CSS2Properties, style,
.
, .
, ,
, . , ,
. , '
(computed style) ,
, :
,
,
.
.
W3C API
getComputedStyle() Window.
, .
, :before
:after, . ,
, , Mozilla
Firefox .
getComputedStyle()
null .
getComputedStyle() CSS2Properties,
, .
CSS2Properties, ,
, getComputedStyle(), .
IE getComputedStyle(),
: HTML currentStyle,
.
(API) IE ,
.
,
, :
var p = document.getElementsByTagName("p")[0]; //
var typeface = "";
//
if (p.currentStyle)
// IE API
typeface = p.currentStyle.fontFamily;
else if (window.getComputedStyle)
// W3C API
typeface = window.getComputedStyle(p, null).fontFamily;
,
.
.
CSS fontfamily ,
. fontFamily
396
, fontfamily,
. , arial, helve
tica, sansserif,
. , ,
top left
"auto". CSS
, , , , .
16.5. CSS
CSS style
class className HTML
.
, , ,
, ,
. 18.3,
. JavaScript
className valid ()
invalid () ,
. 18.2 ,
"valid" "invalid" ,
.
, HTML class
className, . ,
className ,
(,
, 18).
, ,
className
className. 16.7 .
, .
16.7. className
/**
* CSSClass.js: CSS HTML.
*
* CSSClass.
* class
* ( className) HTML. :
* e, CSS
* , CSS c, ,
* . e ,
* id
* document.getElementById().
*/
var CSSClass = {}; //
// true, e , false.
CSSClass.is = function(e, c) {
if (typeof e == "string") e = document.getElementById(e); // id
16.6.
397
// ,
// .
var classes = e.className;
if (!classes) return false;
//
if (classes == c) return true; //
//
// \b .
return e.className.search("\\b" + c + "\\b") != 1;
};
// c className e,
// .
CSSClass.add = function(e, c) {
if (typeof e == "string") e = document.getElementById(e); // id
if (CSSClass.is(e, c)) return; //
if (e.className) c = " " + c; // ,
e.className += c;
//
};
// ( ) c
// className e
CSSClass.remove = function(e, c) {
if (typeof e == "string") e = document.getElementById(e); // id
// className c "".
// \s* .
// "g"
e.className = e.className.replace(new RegExp("\\b"+ c+"\\b\\s*", "g"), "");
};
16.6.
CSS:
.
,
.
16.6.1.
. HTML DOM Level 2 dis
abled <link> <style>. HTML
, JavaScript.
, disabled true, ,
<link> <style>, ,
.
16.8. HTML,
.
,
.
398
16.8.
<head>
<! <link> <style> . >
<! >
<! . >
<! id, . >
<link rel="stylesheet" type="text/css" href="ss0.css" id="ss0">
<link rel="alternate stylesheet" type="text/css" href="ss1.css"
id="ss1" title=" ">
<link rel="alternate stylesheet" type="text/css" href="ss2.css"
id="ss2" title=" ">
<style id="ss3" title="Sans Serif">
body { fontfamily: sansserif; }
</style>
<script>
// id.
// <link> <style>.
function enableSS(sheetid, enabled) {
document.getElementById(sheetid).disabled = !enabled;
}
</script>
</head>
<body>
<! HTML, . >
<! , >
<! . >
<form>
<input type="checkbox"
onclick="enableSS('ss0', this.checked)" checked>
<br><input type="checkbox"
onclick="enableSS('ss1', this.checked)">
<br><input type="checkbox"
onclick="enableSS('ss2', this.checked)">
<br><input type="checkbox"
onclick="enableSS('ss3', this.checked)" checked>Sans Serif
</form>
</body>
16.6.2.
<link> <style>,
, DOM Level 2 API
, .
(API)
Firefox.
IE 5 ,
( )
.
,
. ,
16.6.
399
className
. ,
,
(
cookie).
,
, .
Firefox IE, .
, , styleSheets[]
.
, :
var ss = document.styleSheets[0]
CSSStyleSheet. :
, <link> <style>,
. CSSStyleSheet
cssRules[], :
var firstRule = document.styleSheets[0].cssRules[0];
IE cssRules,
rules.
cssRules[] rules[] CSSRule.
W3C CSSRule CSS
, @', @import @page. IE
CSSRule .
CSSRule ,
. ( W3C DOM , ,
, ,
.) selectorText CSS ,
style CSS2Properties, ,
. , CSS2Properties
HTML style.
CSS2Properties
.
, .
cssText CSS2Properties,
.
, :
//
var ss = document.styleSheets[0];
// , W3C IE API
var rules = ss.cssRules?ss.cssRules:ss.rules;
//
for(var i = 0; i < rules.length; i++) {
var rule = rules[i];
400
. W3C CSSStyleSheet
insertRule() deleteRule(), :
document.styleSheets[0].insertRule("H1 { textweight: bold; }", 0);
IE insertRule() deleteRule(),
addRule() removeRule().
( ) , addRule()
.
16.9 Stylesheet,
(API) W3C IE
.
16.9.
/**
* Stylesheet.js: CSS.
*
* Stylesheet,
* document.styleSheets[].
* .
**/
// Stylesheet,
// CSSStylesheet.
// ss , styleSheet[].
function Stylesheet(ss) {
if (typeof ss == "number") ss = document.styleSheets[ss];
this.ss = ss;
}
// .
Stylesheet.prototype.getRules = function() {
// W3C, ,
// IE
return this.ss.cssRules?this.ss.cssRules:this.ss.rules;
}
// . s ,
// . , s ,
// , .
Stylesheet.prototype.getRule = function(s) {
16.6.
var rules = this.getRules();
if (!rules) return null;
if (typeof s == "number") return rules[s];
// , s
// ,
// .
s = s.toLowerCase();
for(var i = rules.length1; i >= 0; i) {
if (rules[i].selectorText.toLowerCase() == s) return rules[i];
}
return null;
};
// CSS2Properties .
// .
Stylesheet.prototype.getStyles = function(s) {
var rule = this.getRule(s);
if (rule && rule.style) return rule.style;
else return null;
};
// .
Stylesheet.prototype.getStyleText = function(s) {
var rule = this.getRule(s);
if (rule && rule.style && rule.style.cssText) return rule.style.cssText;
else return "";
};
// .
// .
// n. n ,
// .
Stylesheet.prototype.insertRule = function(selector, styles, n) {
if (n == undefined) {
var rules = this.getRules();
n = rules.length;
}
if (this.ss.insertRule) // W3C API
this.ss.insertRule(selector + "{" + styles + "}", n);
else if (this.ss.addRule) // IE API
this.ss.addRule(selector, styles, n);
};
// .
// s , .
// s , .
// s , .
Stylesheet.prototype.deleteRule = function(s) {
// s ,
//
if (s == undefined) {
var rules = this.getRules( );
s = rules.length1;
}
401
402
};
13, JavaScript
, .
,
. , ,
,
. JavaScript
, (event handler) Java
Script JavaScript
. , ,
.
: ,
(. . , ), .
,
( 14) ,
. ,
, ,
,
.
JavaScript.
, ,
, 14.1 14.7,
.
JavaScript
. JavaScript
.
. , ,
404
17.
,
.1 .
( )
.
HTML 4
(API) DOM Level 0. ,
, JavaScript,
.
DOM
2. , Inter
net Explorer.
Internet Explorer
IE 4 IE 5. ,
.
Microsoft
DOM Level 2
IE 5.5 IE 6,
.2
, JavaScript IE
,
.
.
,
, onload.
.
17.1.
JavaScript, HTML
, onclick. ,
,
.
17.1.1.
.
,
1
Netscape 4 ,
.
, .
IE 7
, ,
.
405
17.1.
.
, ,
Submit, , ,
Reset .
, JavaScript
. ,
, .
HTML
( JavaScript).
, ,
, onmouseover <a>,
. ,
Submit, onclick <input>,
, onsubmit <form>, .
,
.
. 17.1, ,
HTML .
JavaScript
.
. ,
HTML 4
HTML. . 17.1 , HTML
.
,
. HTML,
, <head>
. ,
, <applet>, <bdo>,
<br>, <font>, <frame>, <frameset>, <head>, <html>, <iframe>, <isindex>, <meta> <style>.
17.1. HTML'
onabort
<img>
onblur
onchange
<select> <input>,
tarea>
onclick
;
mouseup.
false
(. . , ,
)
ondblclick
<select>,
<tex
406
17.
17.1 ()
onerror
<img>
onfocus
onkeydown
. <body>
false
onkeypress
. <body>
false
onkeyup
<body>
onload
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onreset
. <form>
false
onresize
<body>, <frameset>
onselect
<input>, <textarea>
onsubmit
. <form>
, false
onunload
<body>, <frameset>
17.1.1.1.
. 17.1 ,
. (raw events,
input events). ,
, .
.
(semantic events).
,
:
, , .
. , Submit,
: onmousedown, onmouseup onclick.
HTML, Submit,
onsubmit.
17.1.
407
,
, ,
.
(. 13.7),
, , , ,
. , on
submit onchange, :
HTML
, . ,
key mouse,
. ,
, ,
, .
, onclick .
,
.
17.1.2.
, (
) JavaScript,
HTML. ,
JavaScript ,
onclick <input> ( <button>):
<input type="button" value=" " onclick="alert('');">
JavaScript
. JavaScript, '
. :
<input type="button" value=" "
onclick="if (window.numclicks) numclicks++; else numclicks=1;
this.value=' # ' + numclicks;">
, , ,
HTML
. ,
onsubmit
<form>.1
, ,
onsubmit
. ,
validateForm(),
:
<form action="processform.cgi" onsubmit="return validateForm();">
HTML,
, 18.
408
17.
, HTML ,
.
,
on : onClick, onLoad, onMouseOut
. . XHTML,
, .
JavaScript
return, .
. , , JavaScript
(. 4),
. .
17.1.3.
15, HTML
DOM , JavaScript
HTML.
. <input> onclick,
on
click . ( JavaScript ,
HTML JavaSript
.)
HTML, ,
JavaScript, , Java
Sript . :
JavaScript
. :
<input type="button" value=" "
onclick="alert(typeof this.onclick);">
, , func
tion, string. ( :
this , .
this.)
Java
Script, .
, , HTML:
<form name="f1">
<input name="b1" type="button" value=" ">
</form>
document.f1.b1,
,
:
document.f1.b1.onclick=function() { alert('!'); };
, :
17.1.
409
:
. ,
, .
JavaScript.
JavaSript
. , HTML JavaScript
,
. ,
. HTML,
, JavaSript .
, HTML.
JavaScript
, , .
( ),
.
17.1 ,
.
, onclick
.
, ,
. ,
false, .
.
17.1. ,
//
// onclick <a> <area>. this
// false
// .
function confirmLink() {
return confirm(" " + this.href + "?");
}
//
// confirmLink .
// ,
// .
// onload <body>.
function confirmAllLinks() {
for(var i = 0; i < document.links.length; i++) {
document.links[i].onclick = confirmLink;
}
}
410
17.
17.1.3.1.
,
, JavaScript.
, on
submit <form>
. onsubmit
Form .
:
document.myform.onsubmit();
,
,
. , , onclick Link,
.
, . (
, lo
cation Window, 14.)
onsubmit Form, onclick Sub
mit: ,
. ( ,
submit() Form.)
,
, JavaScript
, () HTML. ,
,
, on
click, HTML. (
17.1 ,
onclick,
.) :
var b = document.myform.mybutton; //
var oldHandler = b.onclick;
// HTML
function newHandler() { /* */ }
// , ,
// .
b.onclick = function() { oldHandler(); newHandler(); }
17.1.4. ,
( HTML,
JavaSript)
. , onsubmit
Form ,
, false,
. ,
, :
17.1.
411
<form action="search.cgi"
onsubmit="if (this.elements[0].value.length == 0) return false;">
<input type="text">
</form>
, ,
, false,
. false ,
, onclick, onkeydown, onkeypress,
onmousedown, onmouseup onreset. . 17.1
, false.
false
: ,
URL . ,
true onmouseover. ,
, URL:
<a href="help.htm"
onmouseover="window.status='!!'; return true;">Help</a>
. 14,
. ,
false, .
:
. ,
, .
17.1.5. this
HTML JavaSript
,
. , .
,
, this .
.
, . ,
o mymethod.
:
button.onclick= o.mymethod;
button.onclick
, o.mymethod.
o, button. ,
button, o. this
Button, o. , ,
,
. , , , :
button.onclick = function() { o.mymethod(); }
412
17.
17.1.6.
8.8, JavaScript
. , ,
, , .
HTML JavaScript,
JavaScript. ,
, ,
JavaScript,
. , , HTML
, , .1
, 4 ,
,
. x
, JavaScript
,
. ,
JavaScript
. ,
, .
, HTML,
, .
. ,
( ,
),
, .
, , ,
, . , Button
HTML <input>,
onclick .
form, form Button.
HTML.
<form>
<! "this" >
<! >
<! >
<! >
<input id="b1" type="button" value="Button 1"
onclick="alert(this.form.b2.value);">
<! , >
<! "this" >
<input id="b2" type="button" value="Button 2"
onclick="alert(form.b1.value);">
<! <form> , >
<! "form". >
1
, ,
.
.
17.1.
413
,
, :
<form>, , Document, .1
Window,
JavaScript.
,
JavaScript, HTML , Ja
vaScript. :
<input id="b3" type="button" value="Button 3"
onclick="alert(b4.value);">
JavaScript
:
var b3 = document.getElementById('b3'); //
b3.onclick = function() {
with (document) {
with(this.form) {
with(this) {
alert(b4.value);
}
}
}
}
with
. ,
6.18.
.
,
, . ,
, Window, Document
open(). open ,
window.open(). ,
HTML, Document
Window, open
document.open(). , ,
1
414
17.
window Form (
name="window"). ,
, window.open(), window
Form, Window,
Window window.open()!
, HTML
.
.
, , , , :
<script>function validateForm() { /* */ }</script>
<form onsubmit=return validateForm();">...</form>
,
, , ,
, ,
. ,
, , ,
. , validateForm()
, ,
.
,
, ,
Window. ,
this, <in
put>, Form form, this.form.
Form
Document. , action form.action
getElementById() document.getElementById().
,
, HTML
.
,
,
, .
, ,
!
17.2.
DOM Level 2
, ,
DOM Level 0 (API),
, JavaScript. DOM
Level 2 ,
( ) API Level 0.
415
Level 2
DOM, API Level 0.
.
DOM Level 2 ,
Internet Explorer.
17.2.1.
DOM Level 0
, .
, .
. DOM Level 2 . ,
(
), ( ) , ,
,
.
.
Document .
( )
,
. ( ,
.)
:
,
.
, Level 0.
,
, , ,
Document.
,
: , submit
<form>, .
, mousedown,
, ,
.
, ,
. (
. 17.3 .)
,
stopPropagation() Event, .
Event stopPropagation()
.
, . , <a>
click, , ,
.
, ,
416
17.
,
, preventDefault() Event.
,
.
DOM Level 1
( mouseover) .
, ,
, Level 0.
,
<p> .
onmouseover <p>
Document
, .
, .
Level 0
. Level 2
.
,
.
17.2.2.
API Level 0 ,
HTML JavaScript.
Level 2
addEventListener() . ( DOM
(API) (listener),
(handler).) . ,
. ,
HTML
on. , Level 0 HTML
onmousedown onmousedown, Level 2
"mousedown".
addEventListener() (
),
. ,
Event. (
, ) , stopPro
pagation(). Event
.
addEventListener() .
true,
. false, ,
, ,
,
.
417
, addEventListener()
submit <form>:
document.myform.addEventListener("submit",
function(e) { return validate(e.target); }
false);
mousedown, <div>
, addEventListener() :
var mydiv = document.getElementById("mydiv");
mydiv.addEventListener("mousedown", handleMouseDown, true);
, validate() handleMouseDown()
JavaScript.
, addEventListe
ner(), , .
,
, HTML,
17.1.6.
Level 2 ,
,
.
addEventListener()
,
( ,
)
. , DOM
,
, ,
. ,
, ,
, .
?
. ,
JavaScript, mouseover
. , ,
mouseover
DHTML
. API Level 0 ,
onmouseover Image.
API Level 2
, .
addEventListener() removeEventListener(),
, ,
.
, . ,
mousedown
418
17.
mousemove mouseup, ,
. , mouseup,
.
:
document.removeEventListener("mousemove", handleMouseMove, true);
document.removeEventListener("mouseup", handleMouseUp, true);
17.2.4.
addEventLis
tener().
1
, DOM ,
(, , Text) EventTarget.
Element Document, Window,
, DOM.
419
. Java DOM :
, , Event
Listener c handleEvent().
Java addEventListener() , .
DOM API JavaScript EventListener
addEventListener()
.
JavaScript
,
:
function registerObjectEventHandler(element, eventtype, listener, captures) {
element.addEventListener(eventtype,
function(event) { listener.handleEvent(event); }
captures);
}
,
handleEvent().
, this , ,
.
DOM, Firefox ( ,
Mozilla)
, handleEvent(),
addEventListener().
, , , .
17.2.5.
, DOM Level 2 ,
.
Events . ,
, :
document.implementation.hasFeature("Events", "2.0")
Events API
.
.
Event,
. , MouseEvents
mousedown, mouseup, click
. MouseEvent. ,
, ,
.
. 17.2 ,
, . : DOM Level 2
,
.
420
17.
,
. . 17.2
MutationEvents. Mutation
. , HTML
,
.
17.2. ,
Event
HTMLEvents
Event
MouseEvents
MouseEvent
UIEvents
UIEvent
MutationEvents MutationEvent
, HTMLEvents MouseEvents
, 0. UIEvents
, focus, blur click,
HTML, ,
,
.
, ,
, Event, .
,
. . 17.3
, , .
,
, ,
( B)
,
preventDefault() ( C). HTMLEvents ,
, , HTML
. ,
(
). : ,
, ,
Event .
. 17.3 . 17.1,
Level 0, HTML 4. ,
, ( UIEvents).
DOM Level 2 abort, error, resize
scroll, HTML 4,
dblclick, HTML 4. ( ,
421
, detail ,
click, .)
17.3.
B
abort
Event
<img>, <object>
blur
Event
change
Event
click
MouseEvent
error
Event
focus
Event
load
Event
mousedown
MouseEvent
mousemove
MouseEvent
mouseout
MouseEvent
mouseover
MouseEvent
mouseup
MouseEvent
reset
Event
<form>
resize
Event
scroll
Event
<body>
select
Event
<input>, <textarea>
submit
Event
unload
Event
<body>, <frameset>
DOMActivate
UIEvent
DOMFocusIn
UIEvent
DOMFocusOut
UIEvent
<form>
detail
17.2.6.
, (API) DOM Level 2
(,
) , .
422
17.
,
, . . 17.2
.
.
Event ;
. UIEvent Event:
, UIEvent, Event.
MouseEvent UIEvent. , ,
, click,
, MouseEvent, UIEvent Event.
.
.
17.2.6.1. Event
, HTMLEvents, Event.
, . .
Event
, . Event
( ,
Event ):
type
.
, ,
(, "click" "mouseover").
target
, ; cur
rentTarget.
currentTarget
, (. . ,
).
,
target. ,
this
.
eventPhase
, ,
. Event.CAPTURING_PHASE,
Event.AT_TARGET Event.BUBBLING_PHASE.
timeStamp
Date, , .
bubbles
, , (
) .
423
cancelable
, ,
, preventDefault().
Event :
stopPropagation() preventDefault().
. stopPropagation()
,
.
preventDefault(),
, . preventDefault() API DOM Level 2
false Level 0.
17.2.6.2. UIEvent
UIEvent Event.
, DOMFocusIn, DOMFocusOut DOMActivate.
, ,
UIEvent MouseEvent. UIEvent
,
Event.
view
Window ( DOM ),
.
detail
,
. click, mousedown mouseup
: 1 , 2 3 . (
: ,
, de
tail. detail, 2,
detail, 1.)
DOMActivate 1 2
,
ShiftEnter.
17.2.6.3. MouseEvent
MouseEvent Event UIEvent,
:
button
, ,
mousedown, mouseup click. 0 , 1
, 2 . ,
, , ,
, mouse
move. , Netscape 6 ,
0, 1 2 1, 2 3. Netscape 6.1 .
424
17.
17.2.7.
0,
DOM Level 2.
, Level 2,
Level 0. ,
.
, ,
Level 2, ,
, HTML JavaSript
Level 0.
HTML, ,
event. ,
event . (
, event HTML
IE.)
DOM ,
0 , ,
Level 0
, addEventListener().
, f onclick e
425
( HTML onclick),
:
e.addEventListener("click", f, false);
f, ,
,
Level 0.
17.3.1. Event IE
DOM Level 2, IE
Event. Event,
, Event IE,
Event IE
Event, UIEvent MouseEvent DOM.
Event IE:
type
, .
on (
, "click" "mouseover"). type
DOM.
srcElement
, .
target Event DOM.
button
, . 1
, 2 , 4 .
426
17.
, , 3
, .
button MouseEvent DOM Level 2, ,
, .
clientX, clientY
MouseEvent DOM Level 2
. ,
, ,
.
. , , 14.3.1.
offsetX, offsetY
. , , ,
Image .
DOM Level 2.
altKey, ctrlKey, shiftKey
, Alt, Ctrl Shift
.
MouseEvent DOM Level 2. ,
Event IE metaKey.
keyCode
. keydown keyup,
Unicode keypress.
String.fromCharCode().
.
fromElement, toElement
fromElement mouseover ,
. toElement
mouseout , .
relatedTarget MouseEvent DOM Level 2.
ancelBubble
. true,
.
stopPropagation() Event DOM Level 2.
returnValue
, false
,
.
false . preventDefault()
Event DOM Level 2.
Event IE .
427
17.3.2. Event IE
IE
Event, ,
attachEvent() (
).
. Event IE
event Window. ,
IE Event window.event
event. ,
, , IE , . .
,
.
,
.
Event ,
DOM Level 2.
.
, , , ,
, .
:
function portableEventHandler(e) {
if (!e) e = window.event; // IE
//
}
||
:
function portableEventHandler(event) {
var e = event || window.event;
//
}
17.3.3. IE
IE 4 ,
Level 0: HTML
.
IE 5 attachEvent() detachEvent(),
.
, attachEvent(),
window.event.
function highlight() { /* */ }
document.getElementById("myelt").attachEvent("onmouseover", highlight);
428
17.
IE
, attachEvent() detachEvent()
: .
, IE,
on. , attachEvent() "on
click", "click", addEventListener().
, attachEvent(),
, ,
. ,
attachEvent(), this Win
dow, .
atachEvent()
. ,
,
.
17.3.4. IE
IE, DOM Level 2,
. , Level 2, IE
. Level 2,
, (
),
. IE DOM Level 2
. Event DOM,
Event IE stopPropagation().
,
IE cancelBubble Event true:
window.event.cancelBubble = true;
: cancelBubble
. , window.event
Event, cancelBubble false.
17.3.5.
,
(, ),
,
,
. DOM
. IE 5
setCapture() releaseCapture().
setCapture() releaseCapture() HTML.
setCapture() ,
, ,
. ,
mousedown, mouseup, mousemove, mouseover, mouseout, click dblclick.
429
setCapture()
, releaseCapture()
.
, alert(),
.
, , setCapture(),
onlosecapture, ,
.
setCapture() mouse
down, .
mousemove
releaseCapture() () mouseup.
setCapture() relaseCapture() 17.4
.
(API) Level 0 ,
,
IE.
.
430
17.
17.3.7.
8.8.4.2, Internet Explorer ( 6)
, ,
. :
// ,
function addValidationHandler(form) {
form.attachEvent("onsubmit", function( ) { return validate(); });
}
,
. ,
,
, .
JavaScript Function, (
) , .
IE .
,
IE.
onunload(). ,
, .
17.3.8. : ,
IE
IE DOM Level 2. 17.2
, .
, Handler.add() Handler.remove(),
. ,
addEventListener(),
. IE 5
, :
.
, DOM.
IE
.
this, ,
, 17.2
, .
, ,
Handler.add(), ,
attachEvent().
431
, Handler.remove()
.
17.2. IE
/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
Handler.js
Handler.add() Handler.remove().
:
element: DOM, ,
.
eventType: , ,
.
DOM, "on".
: "click", "load", "mouseover".
handler: ,
.
, , "this"
.
.
Event, .
, DOM: type, target,
currentTarget, relatedTarget, eventPhase, clientX, clientY, screenX,
screenY, altKey, ctrlKey, shiftKey, charCode, stopPropagation()
preventDefault()
Handler.add() Handler.remove() .
Handler.add()
.
Handler.remove() ,
.
:
,
addEventListener() removeEventListener(), Handler.add()
Handler.remove() , false
( ,
).
Internet Explorer, attachEvent(),
Handler.add() Handler.remove() attachEvent()
detachEvent().
this .
Internet Explorer ,
Handler.add() onunload,
.
432
17.
*
* Handler.add() Window _allHandlers,
* , ,
* _handlers.
*/
var Handler = {};
// DOM
// addEventListener() removeEventListener().
if (document.addEventListener) {
Handler.add = function(element, eventType, handler) {
element.addEventListener(eventType, handler, false);
};
Handler.remove = function(element, eventType, handler) {
element.removeEventListener(eventType, handler, false);
};
}
// IE 5 attachEvent() detachEvent()
// ,
// addEventListener removeEventListener.
else if (document.attachEvent) {
Handler.add = function(element, eventType, handler) {
//
// _find() .
if (Handler._find(element, eventType, handler) != 1) return;
// ,
// .
// .
var wrappedHandler = function(e) {
if (!e) e = window.event;
// ,
// DOM.
var event = {
_event: e,
// IE
type: e.type, //
target: e.srcElement, //
currentTarget: element, //
relatedTarget: e.fromElement?e.fromElement:e.toElement,
eventPhase: (e.srcElement==element)?2:3,
//
clientX: e.clientX, clientY: e.clientY,
screenX: e.screenX, screenY: e.screenY,
//
altKey: e.altKey, ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey, charCode: e.keyCode,
//
stopPropagation: function(){this._event.cancelBubble = true;},
preventDefault: function() {this._event.returnValue = false;}
}
433
,
.
Function.call() ,
(Function.prototype.call)
handler.call(element, event);
else {
// Function.call ,
// .
element._currentHandler = handler;
element._currentHandler(event);
element._currentHandler = null;
}
};
// .
element.attachEvent("on" + eventType, wrappedHandler);
//
//
//
//
//
,
. ,
.
remove()
// .
var h = {
element: element,
eventType: eventType,
handler: handler,
wrappedHandler: wrappedHandler
};
// , .
// "document"
// , ,
// document.
var d = element.document || element;
// window, .
var w = d.parentWindow;
// ,
// .
var id = Handler._uid(); //
if (!w._allHandlers) w._allHandlers = {}; // ,
w._allHandlers[id] = h; //
// .
if (!element._handlers) element._handlers = [];
element._handlers.push(id);
// onunload
// , .
if (!w._onunloadHandlerRegistered) {
w._onunloadHandlerRegistered = true;
w.attachEvent("onunload", Handler._removeAllHandlers);
}
434
17.
};
Handler.remove = function(element, eventType, handler) {
// element._handlers[].
var i = Handler._find(element, eventType, handler);
if (i == 1) return; // ,
//
// .
var d = element.document || element;
var w = d.parentWindow;
// .
var handlerId = element._handlers[i];
// .
var h = w._allHandlers[handlerId];
// , .
element.detachEvent("on" + eventType, h.wrappedHandler);
// element._handlers.
element._handlers.splice(i, 1);
// _allHandlers.
delete w._allHandlers[handlerId];
};
// element._handlers
// 1,
Handler._find = function(element, eventType, handler) {
var handlers = element._handlers;
if (!handlers) return 1; // ,
//
//
var d = element.document || element;
var w = d.parentWindow;
// , ,
// . ,
// , ,
// , .
for(var i = handlers.length1; i >= 0; i) {
var handlerId = handlers[i]; //
var h = w._allHandlers[handlerId]; //
// , , .
if (h.eventType == eventType && h.handler == handler)
return i;
}
return 1; //
};
Handler._removeAllHandlers = function() {
// onunload
// attachEvent. , this
// window, .
var w = this;
//
for(id in w._allHandlers) {
17.4.
435
//
var h = w._allHandlers[id];
//
h.element.detachEvent("on" + h.eventType, h.wrappedHandler);
// window
delete w._allHandlers[id];
}
}
//
//
Handler._counter = 0;
Handler._uid = function() { return "h" + Handler._counter++; };
}
17.4.
, ,
,
. .
17.4.1.
, clientX clientY
.
, . .
.
, ,
,
. 17.3 16.4. 16.4
.
Tooltip.schedule(),
, .
, schedule()
Geometry, 14.2.
17.3.
// schedule(), .
// , ,
// , .
Tooltip.X_OFFSET = 25; //
Tooltip.Y_OFFSET = 15; //
Tooltip.DELAY = 500; // mouseover
/**
*
* Tooltip.DELAY .
* e mouseover.
* ,
* .
436
17.
* , "tooltip"
* .
* onmouseout .
* .
*/
Tooltip.prototype.schedule = function(target, e) {
// . .
var text = target.getAttribute("tooltip");
if (!text) return;
// .
// Geometry.
var x = e.clientX + Geometry.getHorizontalScroll();
var y = e.clientY + Geometry.getVerticalScroll();
// , .
x += Tooltip.X_OFFSET;
y += Tooltip.Y_OFFSET;
// .
var self = this; //
var timer = window.setTimeout(function() { self.show(text, x, y); },
Tooltip.DELAY);
// onmouseout,
// .
if (target.addEventListener) target.addEventListener("mouseout", mouseout,
false);
else if (target.attachEvent) target.attachEvent("onmouseout", mouseout);
else target.onmouseout = mouseout;
//
function mouseout() {
self.hide(); // , ,
window.clearTimeout(timer); //
// , ..
if (target.removeEventListener)
target.removeEventListener("mouseout", mouseout, false);
else if (target.detachEvent)
target.detachEvent("onmouseout",mouseout);
else target.onmouseout = null;
}
}
// Tooltip
Tooltip.tooltip = new Tooltip();
/*
* schedule()
* tooltip
* :
*
* <a href="www.davidflanagan.com" tooltip="good Java/JavaScript blog"
* onmouseover="Tooltip.schedule(this, event)">David Flanagan's blog</a>
*/
Tooltip.schedule = function(target, e) {Tooltip.tooltip.schedule(target, e); }
17.4.
437
17.4.2. :
, ,
DOM Level 2 IE,
, , , .
19.4 JavaScript drag(), ,
mousedown,
. drag() DOM,
IE.
drag() . .
, mousedown,
(, ,
, ).
, CSS
position. ,
mousedown.
drag() , mousedown,
mousemove mouseup,
mousedown. mousemove
, mouseup
mousemove. , mousemove mouseup
, . .
, ,
.
, , moveHandler() upHandler(),
, drag()
,
.
17.4.
/**
* Drag.js: HTML.
*
* drag(),
* onmousedown.
* mousemove .
* mouseup .
* , .
* : DOM 2 IE.
*
* :
*
* elementToDrag: , mousedown
*
.
*
. style.left style.top
*
.
*
* event: Event mousedown.
**/
function drag(elementToDrag, event) {
438
17.
// ( )
// ,
var startX = event.clientX, startY = event.clientY;
// ( ) .
// elementToDrag
// , , offsetParent
// body .
var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
// ,
// ,
// moveHandler(). ,
// .
var deltaX = startX origX, deltaY = startY origY;
// mousemove mouseup,
// mousedown.
if (document.addEventListener) { // DOM 2
//
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true);
}
else if (document.attachEvent) { // IE 5+
// IE
// setCapture() , .
elementToDrag.setCapture();
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
// mouseup.
elementToDrag.attachEvent("onlosecapture", upHandler);
}
else { // IE 4
// IE 4 attachEvent() setCapture(),
//
// ,
var oldmovehandler = document.onmousemove; // upHandler()
var olduphandler = document.onmouseup;
document.onmousemove = moveHandler;
document.onmouseup = upHandler;
}
// , .
if (event.stopPropagation) event.stopPropagation( ); // DOM 2
else event.cancelBubble = true; // IE
// .
if (event.preventDefault) event.preventDefault( ); // DOM 2
else event.returnValue = false; // IE
/**
* mousemove
* . .
**/
function moveHandler(e) {
if (!e) e = window.event; // IE
17.4.
439
// ,
// .
elementToDrag.style.left = (e.clientX deltaX) + "px";
elementToDrag.style.top = (e.clientY deltaY) + "px";
// .
if (e.stopPropagation) e.stopPropagation( ); // DOM 2
else e.cancelBubble = true; // IE
}
/**
* mouseup,
* .
**/
function upHandler(e) {
if (!e) e = window.event; // IE
// .
if (document.removeEventListener) { // DOM
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true);
}
else if (document.detachEvent) { // IE 5+
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture();
}
else { // IE 4
// ,
document.onmouseup = olduphandler;
document.onmousemove = oldmovehandler;
}
// .
if (e.stopPropagation) e.stopPropagation( ); // DOM 2
else e.cancelBubble = true; // IE
}
}
, drag()
HTML ( 16.3,
).
<script src="Drag.js"></script> <! Drag.js >
<! >
<div style="position:absolute; left:100px; top:100px; width:250px;
backgroundcolor: white; border: solid black;">
<! "", . >
<! onmousedown. >
<div style="backgroundcolor: gray; borderbottom: dotted black;
padding: 3px; fontfamily: sansserif; fontweight: bold;"
onmousedown="drag(this.parentNode, event);">
<! "" >
</div>
<! >
440
17.
<p> . , .
<p> .<p>.
</div>
onmousedown <div>.
drag() DOM
IE, Level 0.
drag().
, ,
Shift:
<script src="Drag.js"></script>
<img src="draggable.gif" width="20" height="20"
style="position:absolute; left:0px; top:0px;"
onmousedown="if (event.shiftKey) drag(this, event);">
17.5.
, ,
. ,
:
Events DOM Level 2, IE Mozilla
. ,
.
, ,
.
,
, .
, Firefox IE
, .
,
Keymap,
JavaScript, .
17.5.1.
: keydown, keypress keyup,
onkeydown, onkeypress onkeyup. ,
, : key
down, keypress keyup.
, keydown keyup
keypress,
, .
keypress
: , ,
. keydown keyup
,
, ,
. ASCII
17.5.
441
ASCII, .
Shift 2, key
down , Shift2. keypress
,
@. (
.)
, ,
Backspace, Enter, Escape, , Page Up, Page Down
F1 F12, keydown keyup.
keypress. IE keypress
, ASCII, . .
. ,
, ,
keydown. , 37
( , ).
, , keydown
, keypress
.
17.5.2.
, keydown, keypress keyup,
,
.
Firefox IE.
Alt, Ctrl
Shift, altKey, ctrlKey shiftKey
. :
Firefox, IE . (
Alt IE
, keypress.)
. Firefox .
keyCode
keydown. charCode ,
, keypress. Firefox
keypress
charCode , keyCode .
IE keyCode,
. keydown keyCode
, keypress .
String.fromCharCode().
, .
17.6, ,
( ,
).
442
17.
17.5.3.
<input> <text
area> , . ,
, :
: <input id="surname" type="text"
onkeyup="this.value = this.value.toUpperCase();">
<input>
value. , keyup,
value ,
.
, DOM Level 0.
, ,
. ( :
, onkeyup .
, , ,
onchange.
18.)
onkeypres,
,
. 17.5
, .
<input type=text>, ()
allowed. keypress
, allowed. ,
17.5, HTML,
.
17.5.
/**
* InputFilter.js: <input>
*
* <input type="text"> ,
* "allowed".
* onkeypress
* , allowed.
* <input> "messageid",
* id .
* ,
* messageid. ,
* messageid .
* , .
* CSS .
*
* HTML, .
* :
* <input id="zip" type="text" allowed="0123456789" messageid="zipwarn">
17.5.
443
,
(e.charCode == 0) return true; // ( Firefox)
(e.ctrlKey || e.altKey) return true; // Ctrl Alt
(code < 32) return true; // ASCII
//
var allowed = this.getAttribute("allowed"); //
var messageElement = null; //
var messageid = this.getAttribute("messageid"); // id ,
//
if (messageid) // messageid,
messageElement = document.getElementById(messageid);
//
444
17.
var c = String.fromCharCode(code);
// ,
if (allowed.indexOf(c) != 1) {
// c , ,
if (messageElement) messageElement.style.visibility = "hidden";
return true; //
}
else {
// c ,
if (messageElement) messageElement.style.visibility = "visible";
// keypress
if (e.preventDefault) e.preventDefault();
if (e.returnValue) e.returnValue = false;
return false;
}
}
})(); // .
17.5.4. Keymap
, ,
, ,
. ( HTML)
,
. .
DHTML,
. 17.6 , .
Keymap,
, Escape, Delete, Alt_Z alt_ctrl_shift_F5,
JavaScript, .
Keymap() JavaScript,
,
.
bind() unbind(). Keymap
HTML ( Document) install().
onkeydown
onkeypress
, .
17.6 ,
. ,
.
17.6. Keymap
/*
*
*
*
*
*
Keymap.js: .
Keymap.
( )
. Keymap HTML
17.5.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
keydown keypress. ,
.
Keymap JavaScript,
.
,
.
Keymap
bind(),
.
unbind(), .
Keymap, install(),
HTML, document. install()
onkeypress onkeydown,
, .
,
,
, .
,
, (. ), .
Keymap HTML.
,
, ,
.
,
. :
"A", "7", "F2", "PageUp", "Left", "Delete", "/", "~".
, ,
, .
, ,
KeyEvent.DOM_VK_, Firefox.
"DOM_VK_"
. ,
DOM_VK_BACK_SPACE BACKSPACE.
Keymap.keyCodeToFunctionKey .
,
Alt_, Ctrl_ Shift_.
, ,
.
,
: "Shift_A", "ALT_F2" "alt_ctrl_delete".
: "ctrl_alt_delete" ,
.
, Shift,
. , Shift2 "@".
Alt Ctrl,
445
446
17.
* . ,
* Ctrl_Shift_2, Ctrl_@.
*
*
*
* , :
* 1) HTML,
* 2)
* 3) keydown
*
*
*
*
* "default". ,
* .
*
*
*
* .
* (, AltF4).
*
* (, CtrlS).
* .
*
* ,
* .
* Ctrl
* Alt , .
*/
//
function Keymap(bindings) {
this.map = {}; // identifier>handler
if (bindings) { //
//
for(name in bindings) this.map[name.toLowerCase( )] = bindings[name];
}
}
//
Keymap.prototype.bind = function(key, func) {
this.map[key.toLowerCase()] = func;
};
//
Keymap.prototype.unbind = function(key) {
delete this.map[key.toLowerCase()];
};
// Keymap HTML
Keymap.prototype.install = function(element) {
//
var keymap = this;
function handler(event) { return keymap.dispatch(event); }
//
17.5.
if (element.addEventListener) {
element.addEventListener("keydown", handler, false);
element.addEventListener("keypress", handler, false);
}
else if (element.attachEvent) {
element.attachEvent("onkeydown", handler);
element.attachEvent("onkeypress", handler);
}
else {
element.onkeydown = element.onkeypress = handler;
}
};
// keyCode
// , .
// IE Firefox .
//
// .
Keymap.keyCodeToFunctionKey = {
8:"backspace", 9:"tab", 13:"return", 19:"pause", 27:"escape", 32:"space",
33:"pageup", 34:"pagedown", 35:"end", 36:"home", 37:"left", 38:"up",
39:"right", 40:"down", 44:"printscreen", 45:"insert", 46:"delete",
112:"f1", 113:"f2", 114:"f3", 115:"f4", 116:"f5", 117:"f6", 118:"f7",
119:"f8", 120:"f9", 121:"f10", 122:"f11", 123:"f12",
144:"numlock", 145:"scrolllock"
};
//
// keydown , .
// ASCII,
// . :
// .
Keymap.keyCodeToPrintableChar = {
48:"0", 49:"1", 50:"2", 51:"3", 52:"4", 53:"5", 54:"6", 55:"7", 56:"8",
57:"9", 59:";", 61:"=", 65:"a", 66:"b", 67:"c", 68:"d",
69:"e", 70:"f", 71:"g", 72:"h", 73:"i", 74:"j", 75:"k", 76:"l", 77:"m",
78:"n", 79:"o", 80:"p", 81:"q", 82:"r", 83:"s", 84:"t", 85:"u", 86:"v",
87:"w", 88:"x", 89:"y", 90:"z", 107:"+", 109:"", 110:".", 188:",",
190:".", 191:"/", 192:"`", 219:"[", 220:"\\", 221:"]", 222:"\""
};
// .
Keymap.prototype.dispatch = function(event) {
var e = event || window.event; // IE
// ,
var modifiers = ""
var keyname = null;
if (e.type == "keydown") {
var code = e.keyCode;
// keydown Shift, Ctrl Alt
if (code == 16 || code == 17 || code == 18) return;
//
keyname = Keymap.keyCodeToFunctionKey[code];
447
448
17.
// ,
// Ctrl Alt,
if (!keyname && (e.altKey || e.ctrlKey))
keyname = Keymap.keyCodeToPrintableChar[code];
// , .
// keydown.
if (keyname) {
if (e.altKey) modifiers += "alt_";
if (e.ctrlKey) modifiers += "ctrl_";
if (e.shiftKey) modifiers += "shift_";
}
else return;
}
else if (e.type == "keypress") {
// Ctrl Alt, .
if (e.altKey || e.ctrlKey) return;
//
//
//
if
Firefox keypress .
,
.
(e.charCode != undefined && e.charCode == 0) return;
17.6. onload
449
// , .
// : preventDefault
// ,
// F1 .
if (e.stopPropagation) e.stopPropagation(); // DOM
else e.cancelBubble = true;
// IE
if (e.preventDefault) e.preventDefault();
// DOM
else e.returnValue = false;
// IE
return false;
//
}
};
17.6. onload
JavaScript, ,
, , ,
(
13.5.7). ,
onload Window,
, .
,
onload,
, 17.7.
17.7. onload
/*
* runOnLoad.js: onload.
*
* runOnLoad(),
* ,
* ,
* DOM.
*
* , runOnLoad(),
* .
* this.
* , runOnLoad(),
* .
* , runOnLoad().
*
* , addEventListener() attachEvent(),
* window.onload
* DOM 0. ,
* onload <body> <frameset>.
*/
function runOnLoad(f) {
if (runOnLoad.loaded) f();
// , f().
else runOnLoad.funcs.push(f); //
}
runOnLoad.funcs = []; // ,
//
450
17.
runOnLoad.loaded = false; // .
// .
// runOnLoad.run() :
// . runOnLoad()
// .
runOnLoad.run = function() {
if (runOnLoad.loaded) return; // ,
for(var i = 0; i < runOnLoad.funcs.length; i++) {
try { runOnLoad.funcs[i](); }
catch(e) { /* , ,
*/ }
}
runOnLoad.loaded = true; // .
delete runOnLoad.funcs; // .
delete runOnLoad.run;
// !
};
// runOnLoad.run() onload
if (window.addEventListener)
window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;
17.7.
, DOM Level 2 IE,
,
. ,
, (
,
). DOM Level 0
,
.
,
addEventListener() attachEvent(),
, .
DOM Do
cument.createEvent(), Event.init
Event(), UIEvent.initUIEvent() MouseEvent.initMouseEvent(),
dispatchEvent() , .
IE Document.createEventOb
ject fireEvent() . 17.8
.
,
dataavailable, ,
.
, , dispatch
Event() fireEvent(),
. ,
17.7.
451
, dispatchEvent() fireEvent() .
,
,
. setTimeout()
.
, ,
. ,
,
.
17.8 dataavailable.
17.8.
/**
* DataEvent.js: ondataavailable.
*
* , DataEvent.send() DataEvent.receive(),
* dataavailable
* . ,
* Firefox DOM , IE.
*
* DOM
* , IE
* . dataavailable
* , IE,
* .
*
* : DataEvent.send() ,
* ,
* .
* .
*/
var DataEvent = {};
/**
* ondataavailable .
* datatype data,
* . datatype
* ( null),
* , data
* JavaScript, .
*/
DataEvent.send = function(target, datatype, data) {
if (typeof target == "string") target = document.getElementById(target);
// . ,
if (document.createEvent) { // DOM
// .
// "MouseEvents".
var e = document.createEvent("Events");
// , init .
// ,
// .
452
17.
// . Event.initEvent, MouseEvent.initMouseEvent UIEvent.initUIEvent
e.initEvent("dataavailable", true, false);
}
else if (document.createEventObject) { // IE
// IE
var e = document.createEventObject();
}
else return; //
// .
// , .
e.datatype = datatype;
e.data = data;
// .
if (target.dispatchEvent) target.dispatchEvent(e); // DOM
else if (target.fireEvent) target.fireEvent("ondataavailable", e); // IE
};
/**
* ondataavailable .
*/
DataEvent.receive = function(target, handler) {
if (typeof target == "string") target = document.getElementById(target);
if (target.addEventListener)
target.addEventListener("dataavailable", handler, false);
else if (target.attachEvent)
target.attachEvent("ondataavailable", handler);
};
, HTML
JavaScript.
JavaScript. ,
HTML
. , HTML.1
, HTML ,
, , JavaScript,
.
.
. Java
Script . JavaScript
,
.
,
. , , ,
JavaScript
, ,
.
HTML Submit (
,
Enter ). JavaScript
Submit (, , JavaScript
). JavaScript
,
.
1
, HTML XHTML.
, 6 . . . .: , 2008.
454
18.
, ,
JavaScript.
,
. Form JavaScript,
. , ,
JavaScript
, .
18.1. Form
JavaScript Form HTML. 15,
forms[],
Document. ,
. , document.forms[0]
.
:
document.forms[document.forms.length1]
18.2.
455
.
. : onsubmit
Submit. submit()
onsubmit.
onreset .
,
false. JavaScript
,
. :
<form...
onreset="return confirm(' ?')"
>
18.2.
HTML
JavaScript. . 18.1 ,
. ,
. 18.1. HTML'
456
18.
HTML,
, .
18.1, HTML JavaScript,
.
. 18.1 , HTML
JavaScript.
, HTML, ,
type . ,
Form elements[], ,
.
type, ,
. type JavaScript
, .
,
,
.
: Button (), Checkbox ()
. 18.1
JavaScript.
IV Input, Option, Select Textarea.
, .
18.1. HTML'
HTML2
type
Button
<input
type="button"> "button"
<button type="button">
onclick
onclick
File
<input type="file">
"file"
onchange
,
Hidden
<input type="hidden">
"hidden"
,
,
Option
<option>
Select
Select,
Option
onchange
(
)
457
18.2.
HTML2
type
Radio
<input type="radio">
"radio"
onclick
Reset
<input
type="reset"> "reset"
<button type="reset">
onclick
,
Select
<Select>
"selectone" onchange
,
(.
Option)
Select
<select multiple>
"selectmul onchange
tiple"
,
(.
Option).
Submit
<input
type="submit"> "submit"
<button type="submit">
onclick
Text
<input type="text">
"text"
onchange
"textarea"
onchange
Textarea <textarea>
, HTML
, , HTML 18.1,
, . 18.1.
HTML, JavaScript,
.
, HTML.
JavaScript,
elements[] . report(),
, .
,
report().
18.1. HTML',
<form name="everything">
<! HTML " "... >
<table border="border" cellpadding="5"> <! HTML >
<tr>
<td>Username:<br>[1]<input type="text" name="username" size="15"></td>
<td>Password:<br>[2]<input type="password" name="password" size="15"></td>
<td rowspan="4">Input Events[3]<br>
458
18.
18.3.
459
.
, ,
. ,
report().
,
JavaScript, HTML.
function addhandlers(f) {
// .
for(var i = 0; i < f.elements.length; i++) {
var e = f.elements[i];
e.onclick = function() { report(this, 'Click'); }
e.onchange = function() { report(this, 'Change'); }
e.onfocus = function() { report(this, 'Focus'); }
e.onblur = function() { report(this, 'Blur'); }
e.onselect = function() { report(this, 'Select'); }
}
// .
f.clearbutton.onclick = function() {
this.form.textarea.value=''; report(this,'Click');
}
f.submitbutton.onclick = function () {
report(this, 'Click'); return false;
}
f.resetbutton.onclick = function( ) {
this.form.reset( ); report(this, 'Click'); return false;
}
}
// ,
// !
addhandlers(document.everything);
</script>
18.3.
,
HTML, , HTML.
,
JavaScript.
460
18.
18.3.1.
name,
HTML, .
, , Java
Script, ,
.
<form> name, .
. 15,
JavaScript. <form>
name, Form, , ,
forms[] Document,
Document.
name. , 18.1
:
<form name="everything">
Form :
document.everything
, :
document.forms[0]
, :
, ,
.
HTML <img> <applet> name, ,
name <form>. , . .
name.
, Form,
. . ,
zipcode,
address:
document.address.zipcode
, ,
,
( ):
document.forms[1].elements[4]
,
. 18.1
, name
browser. , ,
name .
name,
JavaScript
. ,
18.3.
461
. Radio () 18.1
:
document.everything.browser[0]
document.everything.browser[1]
document.everything.browser[2]
18.3.2.
( ) ,
. , ,
,
.
type
,
.
. 18.1.
form
Form, .
name
, HTML name.
value
, ,
.
Java
Script. Text ( ) Textarea
( )
. Button
, . value
Radio () Checkbox ()
. HTML
value ,
. value,
.
18.3.3.
:
onclick
.
.
onchange
, ,
, .
, . .
, . :
462
18.
, ,
. ,
.
.
onfocus
, .
onblur
, .
18.1 ,
. ,
, Textarea.
.
, this
, .
form, ,
,
Form this.form. , ,
, x, this.form.x.
:
, .
, () HTML,
( onmousedown).
17, 17.5
.
18.3.
463
,
onclick. ,
, , ,
, JavaScript.
onclick false,
. onclick Submit
, onsubmit
.
Button, Submit Reset <button>
<input>. <button> , . .
, value, HTML (
/ ), <button> </but
ton>. <button> <form>
HTML.
Button, <button>,
<input>, type,
. , <button>
value , . .
value.
Button. ,
, <button>,
, Input.
:
document.everything.extras[0] // "extras"
checked.
,
. defaultChecked
, HTML checked;
, .
HTML (
464
18.
18.3.
465
466
18.
Option, options.length
, Option,
options.length . , address
Select country.
:
document.address.country.options.length = 0; //
Option Select,
options[] null. ,
Option, options[], ,
:
// Option Select
// Option, options[11],
// options[10] ...
document.address.country.options[10] = null;
Option .
Select.add() DOM 2,
.
, Option Option(),
Option.
, Select,
options[]. :
// Option
var zaire = new Option("Zaire",
"zaire",
false,
false);
//
//
//
//
text
value
defaultSelected
selected
// Select, options:
var countries = document.address.country; // Select
countries.options[countries.options.length] = zaire;
Select
<optgroup>. <optgroup> label, ,
Select.
, <optgroup>
, , <optgroup>,
options[] Select.
18.3.8. Hidden
, Hidden ()
.
.
Hidden ,
. Hidden
,
. value
, Hidden, , , Hidden
JavaScript.
18.4.
467
18.3.9. Fieldset
, HTML
<fieldset> <label>, ,
JavaScript
. <fieldset> ,
elements[]
. ( <label>.)
elements[], ,
<fieldset>, value,
, .
18.4.
,
JavaScript
.1 JavaScript 18.3,
,
. ,
HTML, CSS ,
,
. ,
required.
, pattern
. 18.2
, . 18.2 ,
.
18.2. HTML'
<script src="Validate.js"></script> <! >
<style>
/*
* Validate.js , "invalid"
* ,
* .
* .
*/
input.invalid { background: #faa; } /* */
input.valid { background: #afa; } /* , */
/* */
1
,
:
, .
, ,
, ,
JavaScript
. ,
.
.
468
18.
. 18.2. ,
</style>
<!
, ,
required pattern.
>
<form>
<! >
: <input type="text" name="name" required><br>
<!
\s* .
\w+
>
: <input type="text" name="email" pattern="^\s*\w+@\w+\.\w+\s*$"><br>
<! \d{6} , >
: <input type="text" name="zip" pattern="^\s*\d{6}\s*$"><br>
<! >
: <input type="text"><br>
<input type="submit">
</form>
18.3 .
: HTML
, ,
onload,
, required pattern
onchange onsubmit.
className ,
, "invalid" "valid",
(invalid) CSS,1
.
1
Google CSS
. ,
Google, ,
.
18.4.
18.3.
/**
* Validate.js: HTML.
*
*
* HTML .
* "required" "pattern",
* , .
*
* "pattern",
* JavaScript,
* onchange,
* . ,
* , .
* ,
* . ,
* ^ $ .
*
* "required" .
* , "required"
* pattern="\S". ,
* ,
*
* , "class"
* "valid". "invalid".
* ,
* CSS, "" .
* :
*
* <! ,
*
, >
* <style>input.invalid { background: #fa0; }</style>
*
* , ,
* . ,
* ,
* , .
*
* ,
* onchange onsubmit,
* , class.
*
*
* .
*/
(function() { // , ,
// init()
if (window.addEventListener) window.addEventListener("load", init, false);
else if (window.attachEvent) window.attachEvent("onload", init);
// ,
// .
function init() {
469
470
18.
//
for(var i = 0; i < document.forms.length; i++) {
var f = document.forms[i]; //
// ,
var needsValidation = false;
//
for(j = 0; j < f.elements.length; j++) {
var e = f.elements[j]; //
// <input type="text">
if (e.type != "text") continue;
// , ,
var pattern = e.getAttribute("pattern");
// e.hasAttribute(),
// IE .
var required = e.getAttribute("required") != null;
// required
// pattern
if (required && !pattern) {
pattern = "\\S";
e.setAttribute("pattern", pattern);
}
// ,
if (pattern) {
//
e.onchange = validateOnChange;
// , onsubmit
needsValidation = true;
}
}
// ,
// onsubmit
if (needsValidation) f.onsubmit = validateOnSubmit;
}
}
// onchange ,
// . , init()
// required pattern.
function validateOnChange() {
var textfield = this;
//
var pattern = textfield.getAttribute("pattern");
//
var value = this.value;
// ,
// ,
// class "invalid".
if (value.search(pattern) == 1) textfield.className = "invalid";
else textfield.className = "valid";
}
// onsubmit ,
// .
18.4.
function validateOnSubmit() {
//
// className .
// ,
// .
var invalid = false; // ,
//
for(var i = 0; i < this.elements.length; i++) {
var e = this.elements[i];
// ,
// onchange
if (e.type == "text" && e.onchange == validateOnChange) {
e.onchange( ); //
// , ,
//
if (e.className == "invalid") invalid = true;
}
}
// ,
//
if (invalid) {
alert(" " +
" .\n" +
", " +
" .");
return false;
}
}
})();
471
Cookies
Document 15
cookie. ,
; cookie ,
: JavaScript
. Cookies
,
,
.
, cookies
HTTP.
cookies Docu
ment.cookie.
, .
.
19.1. cookies
Cookie ,
.1 Cookies
1
cookie () ,
. cookie,
magic cookie, ,
, , ,
. JavaScript cookie
,
(,
HTTPS).
19.1. cookies
473
,
, ,
, , . Cookies
HTTP. cookie
,
cookie,
. , JavaScript cookie
cookie Document.
cookie , , ,
cookies, . cookie
, .
cookie, , cookies,
. , cookies,
cookie.
, . cookie
, cookies , .
cookie
, , .
cookies
. cookie
, ,
. expires,
cookie.
, maxage,
cookie .
cookie ,
.
maxage, cookie.
cookie, path, ,
cookie. cookie
,
. , , http://www.examp'
le.com/catalog/index.html cookie, cookie
http://www.example.com/catalog/order.html http://www.example.com/cata'
log/widgets/index.html, http://www.example.com/about.html.
, , .
cookie
, cookie.
, ,
, .
,
, ,
474
19. Cookies
. , cookie path.
,
URL, cookie. , cookie,
http://www.example.com/catalog/widgets/index.html,
path "/catalog", cookie
http://www.example.com/catalog/order.html. path "/",
cookie www.example.com.
cookies ,
, .
cookies .
, order.example.com cookie,
catalog.example.com.
cookie domain. cookie, catalog.ex'
ample.com, path, "/", domain
".example.com", cookie catalog.ex'
ample.com, orders.example.com example.com.
domain cookie ,
, . ,
, cookie .
cookie secure,
, cookie . cookie
, . . HTTP.
cookie , ,
HTTPS
.
: expires, maxage, path, domain secure
JavaScript. ,
cookie.
Cookies ,
cookies,
, . , cook
ies ,
,
,
cookies . ,
cookie JavaScript, ,
. ,
navigator.cookieEnabled. true,
cookie , false (
cookie,
).
, , ,
, cookies, ,
cookie. , ,
19.2 , .
, cookies (
HTTP), RFC 2965 http://
19.2. cookie
475
www.ietf.org/rfc/rfc2965.txt. cookie
Netscape , Netscape,
. ,
, RFC.
http://wp.netscape.com/newsref/std/cookie_spec.html.
cookie Java
Script expires, path, domain secure.
.
19.2. cookie
cookie ,
cookie :
=
:
document.cookie = "version=" + encodeURIComponent(document.lastModified);
cookie
cookie . cookie
, .
cookie, ,
JavaScript encodeURIComponent().
cookie
decodeURIComponent(). ( ,
escape() unescape().)
cookie
, .
cookie, ,
( ) maxage. ,
cookie :
name=value; maxage=seconds
, cookie, ,
:
document.cookie = "version=" + document.lastModified + "; maxage=" + (60*60*24*365);
, cookie
expires, ,
Date.toGMTString(). :
var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear() + 1);
document.cookie = "version=" + document.lastModified +
"; expires=" + nextyear.toGMTString();
476
19. Cookies
; path=
; domain=
; secure
cookie, ,
. cookie
, maxage expires.
cookie, ( )
, maxage 0 ( expires
). : cookie
,
.
19.2.1. cookie
Cookie ,
.
,
. RFC 2965
cookie.
, , 300 cookies
20 cookies ( ,
) 4 cookie (
cookie ).
300 cookies,
4 cookie .
19.3. cookies
cookie JavaScript,
cookie, .
,
, cookie, .
,
cookie. cookie
String.indexOf() String.substring(), cook
ie String.split().
cookie cookie
, ,
cookie. , cookie
, .
. decodeURIComponent()
cookie, encodeURIComponent().
, cookie,
:
// cookie. cookies .
19.4. cookie
477
, cookie, .
, , ,
.
(value != document.lastModified)
alert(" ");
: , cookie,
cookie.
cookie ,
.
19.4. cookie
cookies 19.2,
, cookies. Cookie()
cookie . store()
cookie, ,
, , remove() cookie, 0
maxage.
Cookie, ,
cookie.
cookie, Cookie.
store(), , ,
cookie.
Cookie Cookie() cookie
, ,
, Cookie.
19.2, 19.1,
, Cookie.
19.1. Cookie
<script src="Cookie.js"></script><! Cookie >
<script>
// cookie,
// .
var cookie = new Cookie("vistordata");
478
//
//
//
if
19. Cookies
, cookie.
( ),
(!cookie.name || !cookie.color) {
cookie.name = prompt(" :", "");
cookie.color = prompt(" :", "");
}
//
if (!cookie.visits) cookie.visits = 1;
else cookie.visits++;
// cookie, .
// cookie 10 . path
// , cookie
// . ,
// cookie "visitordata" .
cookie.store(10);
// , cookie
// ( ), ,
// , .
document.write('<h1 style="color:' + cookie.color + '">' +
' , ' + cookie.name + '!' + '</h1>' +
'<p> ' + cookie.visits + ' .' +
'<button onclick="window.cookie.remove();"> </button>');
</script>
Cookie 19.2.
19.2. Cookie
/**
* Cookie().
*
* cookie .
* cookie , ,
* .
*
* cookie ,
* Cookie.
* "store" "remove", .
* cookie ,
* store().
* cookie , remove().
*
* Cookie.enabled() true,
* cookies ,
* false.
*/
function Cookie(name) {
this.$name = name; // cookie
// cookies,
// .
// Document.cookie.
19.4. cookie
// cookie , .
var allcookies = document.cookie;
if (allcookies == "") return;
// cookies,
// .
var cookies = allcookies.split(';');
var cookie = null;
for(var i = 0; i < cookies.length; i++) {
// cookie ?
if (cookies[i].substring(0, name.length+1) == (name + "=")) {
cookie = cookies[i];
break;
}
}
// cookie ,
if (cookie == null) return;
// cookie
var cookieval = cookie.substring(name.length+1);
// cookie ,
//
// .
// , .
// cookie split().
var a = cookieval.split('&'); //
for(var i=0; i < a.length; i++) //
a[i] = a[i].split(':');
// , cookie,
// Cookie .
// : ,
// store() .
for(var i = 0; i < a.length; i++) {
this[a[i][0]] = decodeURIComponent(a[i][1]);
}
}
/**
* store() Cookie.
*
* :
*
* daysToLive: cookie .
* , cookie .
* null , cookie
* cookie
* .
* maxage cookie.
* path: path cookie
* domain: domain cookie
* secure: true,
* secure cookie
*/
479
480
19. Cookies
19.5. cookies
481
* true , cookies
* . cookies
* , false.
*/
Cookie.enabled = function() {
// navigator.cookieEnabled,
if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;
// ,
if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;
// cookie
document.cookie = "testcookie=test; maxage=10000"; // cookie
// cookie
var cookies = document.cookie;
if (cookies.indexOf("testcookie=test") == 1) {
// Cookie
return Cookie.enabled.cache = false;
}
else {
// Cookie ,
document.cookie = "testcookie=test; maxage=0"; // cookie
return Cookie.enabled.cache = true;
}
}
19.5. cookies
Cookies ,
:
cookie 4 .
cookies
, ,
. cookies ,
.
cookies. Internet Explorer
Flash ( Microsoft Adobe)
.
,
, , , ,
. , IE
Flash, ,
,
IE, Flash cookies.
19.5.1. userData IE
Internet Explorer
DHTML. (
<div>) . CSS:
482
19. Cookies
behavior CSS,
. behavior
JavaScript:
var memory = document.getElementById("memory");
memory.style.behavior = "url('#default#userData')";
HTML userData1,
( behavior).
,
setAttribute(),
save():
var memory = document.getElementById("memory"); // ,
//
memory.setAttribute("username", username);
//
memory.setAttribute("favoriteColor", favoriteColor);
memory.save("myPersistentData");
//
: save() (
), .
, .
, Internet Explorer,
, cookie.
save() expires.
,
Date.toUTCString(). ,
10 , ,
:
var now = (new Date()).getTime();
//
//
var expires = now + 10 * 24 * 60 * 60 * 1000;
//
//
memory.expires = (new Date(expires)).toUTCString(); //
10
,
: load(), ,
getAttribute() :
var memory = document.getElementById("memory");
memory.load("myPersistentData");
1
// ,
//
//
483
19.5. cookies
var user = memory.getAttribute("username");
//
var color = memory.getAttribute("favoriteColor"); //
19.5.1.1.
userData
. ,
userData, XML, .
HTML XMLDocument
, DOM Document.
save()
load()
DOM (. 15). :
var memory = document.getElementById("memory"); //
//
var doc = memory.XMLDocument;
//
var root = doc.documentElement;
//
root.appendChild(doc.createTextNode("data here"));
,
//
XML
, JavaScript
XML.
19.5.1.2.
IE
, cookie. 64 ,
640 .
.
.
19.5.1.3.
cookies , IE,
. , cookies,
IE ,
. ,
IE , cookies path domain.
,
. , , IE,
. ,
, HTTPS, ,
HTTP.
19.5.2. SharedObject
Flash
6 Flash
SharedObject,
484
19. Cookies
ActionScript Flash.1
, ActionScript
SharedObject , . :
( cookie):
var so = SharedObject.getLocal("myPersistentData");
SharedObject load(),
IE. , SharedObject, ,
, .
SaredData data. Ac
tionScript, .
,
data:
var name = so.data.username; //
so.data.favoriteColor = "red"; //
data
, , , , .
SharedObject save(), flush(),
SharedObject.
: data
Flash. ,
, SharedObject
.
, ,
, JavaScript ActionScript
, Flash.
Flash JavaScript,
JavaScript Flash
. , 23. 22.12
ExternalInterface (
Flash 8 ), ActionScript
JavaScript. 19.3 19.4
JavaScript ActionScript.
GetVariable() SetVariable() Flash
JavaScript ActionScript
, ActionScript fscommand()
JavaScript.
1
SharedObject Flash
Adobe : http://www.adobe.com/support/flash/acti'
on_scripts/local_shared_object/.
Flash (Brad Neuberg),
JavaScript AMASS (http://coding'
inparadise.org/projects/storage/README.html).
;
(http://codinginparadise.org).
19.5. cookies
485
19.5.2.1.
Flash 100
.
10 10 . ,
.
, , Flash
.
19.5.2.2.
Flash,
.
. ,
path cookie. SharedObject
SharedObject.getLocal() ,
URL
. , ,
, . ,
SharedObject,
Flash :
var so = SharedObject.getLocal("My/Shared/Persistent/Data", //
"/");
//
SharedObject JavaScript
Flash,
, (.
19.3 ).
19.5.3. :
,
, . 19.3 ,
. PObject Cookie
19.2. PObject()
. ,
onload. JavaScript
,
. ,
,
. , ,
, .
, .
onload
PObject,
JavaScript. ,
PObject (,
486
19. Cookies
), save() PObject,
( ). ,
forget() PObject.
PObject IE
.
Flash
Flash. ,
cookies.1
: PObject
. ,
( : http://www.json.org),
.
19.3 , ,
.
, PObject
(API).
19.3. PObject.js: JavaScript' PObject
/**
* PObject.js: JavaScript,
*
* .
*
* PObject(),
* .
* PObject . save()
* , forget()
* .
* PObject, ,
* JavaScript, save(),
* . "save"
* "forget" ,
* , $. PObject ,
* .
* ,
* .
*
* PObject
* JavaScript,
* PObject , JavaScript.
* : , PObject()
* ,
1
, , cookies
, , IE Flash
, ,
cookie.
19.5. cookies
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
,
onload ,
.
:
PObject(name, defaults, onload):
:
name , .
PObject, PObject
,
.
null ,
( ), .
defaults JavaScript.
(
, PObject )
PObject.
onload , (),
PObject .
:
PObject PObject.
** , PObject() .
PObject .
PObject.save(lifetimeInDays):
PObject ,
.
PObject.forget():
PObject. ""
PObject , , ,
.
:
(API)
PObject,
. Internet Explorer
"UserData". , Flash
Adobe, SharedObject. ,
IE Flash ,
cookie. : Flash
,
, .
PObject:
, PObject ,
487
488
19. Cookies
* , .
* cookie ,
* , ( )
* PObject, .
* Flash
* ,
* .
*
* cookie ,
* , cookie ,
* .
* Flash,
* , Flash.
*
* :
*
* , PObject,
* . ,
* , , PObject
* , ,
* .
*/
//
function PObject(name, defaults, onload) {
if (!name) { // , URL
name = window.location.pathname;
var pos = name.lastIndexOf("/");
if (pos != 1) name = name.substring(pos+1);
}
this.$name = name; //
// init(),
// .
this.$init(name, defaults, onload);
}
// PObject .
PObject.prototype.save = function(lifetimeInDays) {
//
var s = "";
//
for(var name in this) {
//
if (name.charAt(0) == "$") continue; // ,
// $
var value = this[name];
//
var type = typeof value;
//
//
if (type == "object" || type == "function") continue;
if (s.length > 0) s += "&";
// &
//
s += name + ':' + encodeURIComponent(value);
}
// , ,
// .
this.$save(s, lifetimeInDays);
19.5. cookies
489
};
PObject.prototype.forget = function() {
//
// , save().
for(var name in this) {
if (name.charAt(0) == '$') continue;
var value = this[name];
var type = typeof value;
if (type == "function" || type == "object") continue;
delete this[name]; //
}
// ,
// 0.
this.$save("", 0);
};
// / this.
// , .
// $init().
PObject.prototype.$parse = function(s, defaults) {
if (!s) { // ,
if (defaults) for(var name in defaults) this[name] = defaults[name];
return;
}
// ,
// .
// split().
var props = s.split('&');// /
for(var i = 0; i < props.length; i++) { // /
var p = props[i];
var a = p.split(':'); //
this[a[0]] = decodeURIComponent(a[1]); //
//
}
};
/*
* , .
* $init(),
* , $save(), .
*/
// , IE,
// , Flash
//
var isIE = navigator.appName == "Microsoft Internet Explorer";
var hasFlash7 = false;
if (!isIE && navigator.plugins) { //
// Netscape
var flashplayer = navigator.plugins["Shockwave Flash"];
if (flashplayer) { // Flash
//
var flashversion = flashplayer.description;
490
19. Cookies
var flashversion = flashversion.substring(flashversion.search("\\d"));
if (parseInt(flashversion) >= 7) hasFlash7 = true;
}
}
if (isIE) { // IE
// PObject()
PObject.prototype.$init = function(name, defaults, onload) {
// userData
var div = document.createElement("div"); // <div>
this.$div = div;
//
div.id = "PObject" + name;
//
div.style.display = "none";
//
// IE .
// "userData" getAttribute(),
// setAttribute(), load() save() <div>.
// .
div.style.behavior = "url('#default#userData')";
document.body.appendChild(div); //
// .
div.load(name); // ,
// .
// . "data".
var data = div.getAttribute("data");
//
this.$parse(data, defaults);
//
//
//
if
onload,
,
PObject() .
(onload) {
var pobj = this; //
// "this"
setTimeout(function() { onload(pobj, name);}, 0);
}
}
//
PObject.prototype.$save = function(s, lifetimeInDays) {
if (lifetimeInDays) { // ,
//
var now = (new Date()).getTime();
var expires = now + lifetimeInDays * 24 * 60 * 60 * 1000;
//
// <div>
this.$div.expires = (new Date(expires)).toUTCString();
}
//
this.$div.setAttribute("data", s); //
// <div>
this.$div.save(this.$name);
//
};
}
19.5. cookies
else if (hasFlash7) { // Flash
PObject.prototype.$init = function(name, defaults, onload) {
var moviename = "PObject_" + name; // <embed>
var url = "PObject.swf?name=" + name; // URL
// Flash ,
// FSCommand.
// .
var pobj = this; //
// Flash ,
window[moviename + "_DoFSCommand"] = function(command, args) {
// , Flash,
// ,
var data = pobj.$flash.GetVariable("data")
pobj.$parse(data, defaults);//
//
if (onload) onload(pobj, name); // onload,
//
};
// <embed> Flash.
// <object> ,
// FSCommand. :
// Flash IE, .
var movie = document.createElement("embed"); //
movie.setAttribute("id", moviename);
//
movie.setAttribute("name", moviename);
//
movie.setAttribute("type", "application/xshockwaveflash");
movie.setAttribute("src", url); // URL
//
movie.setAttribute("width", 1); // 0,
//
movie.setAttribute("height", 1);
movie.setAttribute("style", "position:absolute; left:0px; top:0px;");
document.body.appendChild(movie); //
this.$flash = movie; //
};
PObject.prototype.$save = function(s, lifetimeInDays) {
// ,
// Flash. ActionScript .
// : Flash
// .
this.$flash.SetVariable("data", s); // Flash
};
}
else { /* IE Flash 7, cookies */
PObject.prototype.$init = function(name, defaults, onload) {
var allcookies = document.cookie; // cookies
var data = null;
// cookie
var start = allcookies.indexOf(name + '='); // cookie
if (start != 1) {
//
start += name.length + 1;
// cookie
var end = allcookies.indexOf(';', start);// cookie
if (end == 1) end = allcookies.length;
491
492
19. Cookies
data = allcookies.substring(start, end); //
}
this.$parse(data, defaults); // cookie
if (onload) {
// onload
var pobj = this;
setTimeout(function() { onload(pobj, name); }, 0);
}
};
PObject.prototype.$save = function(s, lifetimeInDays) {
var cookie = this.$name + '=' + s; // cookie
if (lifetimeInDays != null)
//
cookie += "; maxage=" + (lifetimeInDays*24*60*60);
document.cookie = cookie;
// cookie
};
ActionScript .
SharedObject, , ( JavaScript)
19.6.
493
URL . Sha
redObject ,
. JavaScript
fscommand(),
doFSCommand. , ActionScript
, data
. data JavaScript
SetVariable(), ActionScript
.
ActionScript PObject.as, 19.4,
PObject.swf,
Flash.
ActionScript mtasc ( : http://
www.mtasc.org). :
mtasc swf PObject.swf main header 1:1:1 PObject.as
mtasc SWF,
PObject.main() .
Flash,
PObject.main() .
main() .
19.6.
19.3 ,
, . :
, ,
.
, ,
(, ),
.
: , .
:
, ,
. ,
. ,
.
,
.
( , Windows),
, .
, , cookies
, .
, ,
, .
HTTP
(Hypertext Transfer Protocol, HTTP)
, ,
. ,
HTTP. , ,
HTTP, ,
URL . , , JavaScript
HTTP.
HTTP ,
location Window submit() Form.
,
. HTTP
, ,
.
JavaScript ,
.
<img>, <frame> <script> src.
URL, HTTP GET
URL. ,
, URL
src <img>.
, , ,
: 11 .1
1
20.1. XMLHttpRequest
495
<iframe> HTML ,
<img>, . .
, ,
. <iframe> URL
, , URL
src <iframe>. HTML,
, ,
<iframe>. <iframe>
, .
,
<iframe>. :
, 13.8.2.
src <script>
HTTP. <script>
HTTP ,
JavaScript,
JavaScript .
, <img>, <iframe>
<script> HTTP,
,
, ,
. XMLHttpRequest
HTTP, POST HEAD
GET. XMLHttpRequest
,
DOM. XMLHttpRequest
XML
. XMLHttpRequest
, Ajax1. Ajax
, XMLHttpRequest.
<script>
HTTP, ,
, XMLHttpRequest .
20.1. XMLHttpRequest
HTTP XMLHttp
Request :
XMLHttpRequest.
;
Ajax , , :
, , Ajax . . . .:
, 2007;
, , , AJAX PHP.
. . . .: , 2007. . . .
496
20. HTTP
HTTP .
.
.
.
,
HTTP (. 10).
, . ,
, http.js,
,
:
var HTTP = {};
20.1.1.
XMLHttpRequest ,
Internet Explorer . ( ,
XMLHttpRequest
.)
XMLHttpRequest
:
var request = new XMLHttpRequest();
IE 7 XMLHttpRequest() .
IE 5 6 XMLHttpRequest ActiveX
ActiveXObject(),
:
var request = new ActiveXObject("Msxml2.XMLHTTP");
20.1
HTTP.newRequest(), XMLHttpRequest.
20.1. HTTP.newRequest()
// , XMLHttpRequest.
HTTP._factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
// , .
HTTP._factory = null;
20.1. XMLHttpRequest
497
// XMLHttpRequest.
//
// ,
// , .
// ,
// .
//
HTTP.newRequest = function() {
if (HTTP._factory != null) return HTTP._factory();
for(var i = 0; i < HTTP._factories.length; i++) {
try {
var factory = HTTP._factories[i];
var request = factory();
if (request != null) {
HTTP._factory = factory;
return request;
}
}
catch(e) {
continue;
}
}
// ,
// , .
HTTP._factory = function() {
throw new Error(" XMLHttpRequest ");
}
HTTP._factory(); //
}
20.1.2.
XMLHttpRequest ,
.
. open(),
URL HTTP. HTTP
GET,
URL. , POST;
HTML:
. HEAD:
, URL.
, ,
. URL
:
request.open("GET", url, false);
open() XMLHttpRequest
. false,
. ,
498
20. HTTP
, ,
.
open()
.
, .
open() ,
,
. ,
. :1
request.setRequestHeader("UserAgent", "XMLHttpRequest");
request.setRequestHeader("AcceptLanguage", "en");
request.setRequestHeader("IfModifiedSince", lastRequestTime.toString());
:
cookies. "Cookie"
cookie.
, open()
:
request.send(null);
send() . HTTP
GET null. POST
, (. 20.5).
null. ( :
null . XMLHttpRequest
, Firefox,
, JavaScript.)
20.1.3.
XMLHttpRequest HTTP,
. open() false,
send() : ,
.2
send() . ,
HTTP, sta
tus .
HTTP. 200
. 404
, , URL .
1
HTTP .
,
HTTP, HTTP.
XMLHttpRequest ,
. ,
, ,
send().
20.1. XMLHttpRequest
499
XMLHttpRequest ,
responseText . XML
, DOM Document re
sponseXML. : XMLHttpRequest
Document,
XML, MIME "text/xml".
, ,
send(), :
if (request.status == 200) {
// . .
alert(request.responseText);
}
else {
// . .
alert("Error " + request.status + ": " + request.statusText);
}
XMLHttpRequest HTTP,
. getAllResponseHeaders()
, getResponseHeader()
. :
if (request.status == 200) { //
// , XML
if (request.getResponseHeader("ContentType") == "text/xml") {
var doc = request.responseXML;
//
}
}
XMLHttpRequest
: , send()
.
JavaScript , ,
(, ).
,
URL. XMLHttpRequest
. send()
,
JavaScript XMLHttpRequest
.
XMLHttpRequest
.
20.1.4.
XMLHttpRequest ,
open() true (
500
20. HTTP
, true ).
send() .
,
XMLHttpRequest, .
,
: , .
.
XMLHttpRequest onreadysta
techange. ,
readyState. readyState ,
HTTP,
. 20.1. XMLHttpRequest
, .
20.1. readyState XMLHttpRequest
readyState
open()
open() , send()
send() ,
. 3 readyState Firefox
Internet Explorer ; . 20.1.4.1
a
. . . .
XMLHttpRequest ,
. onreadysta
techange open()
send(). ,
, .
JavaScript, onreadystatechange
. ,
readyState XMLHttpRequest. ,
XMLHttpRequest,
,
.
:
// XMLHttpRequest
var request = HTTP.newRequest();
// .
//
// , .
request.onreadystatechange = function() {
if (request.readyState == 4) {
//
if (request.status == 200)
//
alert(request.responseText); //
20.1. XMLHttpRequest
501
}
}
// GET URL. ,
//
request.open("GET", url);
//
// .
// . GET,
// null. , send()
// .
request.send(null);
20.1.4.1. 3
readyState
XMLHttpRequest ,
3 readyState. ,
Firefox on
readystatechange 3 readyState
.
. , Internet Exp
lorer
readyState. ,
Internet Explorer 3
readyState , .
3 readyState.
, 3 , ,
Microsoft XMLHttpRequest
, responseText
. , , responseText
, .
,
XMLHttpRequest.
XMLHttpRequest
, readyState, 4.
20.1.5. XMLHttpRequest
(. 13.8.2),
XMLHttpRequest HTTP ,
, .
, , ,
, URL
, .
XMLHttpRequest :
XMLHttpRequest HTTP
URL. ,
URL, file://. ,
502
20. HTTP
, XMLHttpRequest
.
( ).
HTTP, HTTP.
20.2.
XMLHttpRequest
HTTP.ne
wRequest(), XMLHttpRequest .
XMLHttpRequest.
.
20.2.1. GET
20.2 ,
XMLHttpRequest:
URL , .
20.2. HTTP.getText()
/**
* XMLHttpRequest
* URL GET. ,
* ( ) .
*
* .
*/
HTTP.getText = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
callback(request.responseText);
}
request.open("GET", url);
request.send(null);
};
20.3 ,
XML .
20.3. HTTP.getXML()
HTTP.getXML = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
callback(request.responseXML);
}
request.open("GET", url);
request.send(null);
};
20.2. XMLHttpRequest
503
20.2.2.
XMLHttpRequest ,
HTTP. HTTP HEAD
URL ,
. , ,
, .
20.4 , HEAD.
, HTTP
JavaScript.
,
404 .
20.4. HTTP.getHeaders()
/**
* HTTP HEAD
* URL.
* HTTP.parseHeaders()
* . ,
* errorHandler. ,
* null .
*/
HTTP.getHeaders = function(url, callback, errorHandler) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
callback(HTTP.parseHeaders(request));
}
else {
if (errorHandler) errorHandler(request.status,
request.statusText);
else callback(null);
}
}
}
request.open("HEAD", url);
request.send(null);
};
// , XMLHttpRequest,
// .
HTTP.parseHeaders = function(request) {
var headerText = request.getAllResponseHeaders(); //
var headers = {}; //
var ls = /^\s*/; // ,
var ts = /\s*$/; // ,
//
var lines = headerText.split("\n");
//
for(var i = 0; i < lines.length; i++) {
var line = lines[i];
504
20. HTTP
if (line.length == 0) continue; //
//
var pos = line.indexOf(':');
var name = line.substring(0, pos).replace(ls, "").replace(ts, "");
var value = line.substring(pos+1).replace(ls, "").replace(ts, "");
// JavaScript
headers[name] = value;
}
return headers;
};
20.2. XMLHttpRequest
505
if (errorHandler) errorHandler(request.status,
request.statusText);
else callback(null);
}
}
}
request.open("POST", url);
// , .
request.setRequestHeader("ContentType",
"application/xwwwformurlencoded");
//
// .
request.send(HTTP.encodeFormData(values));
};
/**
* ,
* , application/xwwwformurlencoded
*/
HTTP.encodeFormData = function(data) {
var pairs = [];
var regexp = /%20/g; // ,
for(var name in data) {
var value = data[name].toString();
// /, .
// , ,
// encodeURIComponent, %20
// "+". String.replace()
var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
encodeURIComponent(value).replace(regexp,"+");
pairs.push(pair);
}
// , &
return pairs.join('&');
};
POST XMLHttpRequest
21.14. ,
XML.
506
20. HTTP
, .
,
text/xml, XML
responseXML. DOM
Document,
DOM.
, XML
. ,
JavaScript,
XML
, XMLHttpRequest
DOM ,
. ,
,
JavaScript .
, eval().
JavaScript
JSON (JavaScript Object Notation JavaScript).1
XML JSON:
<! XML >
<author>
<name>Wendell Berry</name>
<books>
<book>The Unsettling of America</book>
<book>What are People For?</book>
</books>
</author>
// JSON
{
"name": "Wendell Berry",
"books": [
"The Unsettling of America",
"What are People For?"
]
}
HTTP.post(), 20.5,
HTTP._getResponse(). ContentType
. 20.6
HTTP_getResponse(), XML Docu
ment, eval() JavaScript JSON
, .
1
JSON http://json.org.
(Douglas Crockford);
/ JSON,
.
, JavaScript.
20.2. XMLHttpRequest
507
20.6. HTTP._getResponse()
HTTP._getResponse = function(request) {
// ,
switch(request.getResponseHeader("ContentType")) {
case "text/xml":
// XML, Document.
return request.responseXML;
case "text/json":
case "text/javascript":
case "application/javascript":
case "application/xjavascript":
// JavaScript JSON, eval(),
// JavaScript.
// : ,
// !
return eval(request.responseText);
default:
//
// .
return request.responseText;
}
};
eval() JSON,
20.6, ,
JSON.
eval()
JavaScript , eval().
20.2.5.
XMLHttpRequest
.
. ,
send()
. ,
send() ,
.
. , XMLHttpRe
quest HTTP, .
,
, .
,
? ,
.
,
Windows.setTimeout()
HTTP. ,
,
Window.clearTimeout(), .
, ,
508
20. HTTP
readyState 4,
XMLHttpRequest.abort().
,
(, Window.alert()).
,
.
20.7 HTTP.get(),
.
HTTP.getText() 20.2
, ,
, HTTP._getResponse(),
. ,
, ,
onreadystatechange readyState,
4. , Firefox,
3,
.
20.7. HTTP.get()
/**
* HTTP GET URL.
*
* ContentType .
* options.
*
* (,
* 404 Not Found),
* options.errorHandler. ,
* null .
*
* options.parameters ,
* . HTTP.encodeFormData()
* , URL,
* URL '?'.
*
* options.progressHandler,
* , readyState , 4.
* .
*
* options.timeout, XMLHttpRequest
* , .
*
* options.timeoutHandler,
* URL .
*
**/
HTTP.get = function(url, callback, options) {
var request = HTTP.newRequest();
var n = 0;
var timer;
if (options.timeout)
20.3. Ajax
509
timer = setTimeout(function() {
request.abort();
if (options.timeoutHandler)
options.timeoutHandler(url);
},
options.timeout);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (timer) clearTimeout(timer);
if (request.status == 200) {
callback(HTTP._getResponse(request));
}
else {
if (options.errorHandler)
options.errorHandler(request.status,
request.statusText);
else callback(null);
}
}
else if (options.progressHandler) {
options.progressHandler(++n);
}
}
var target = url;
if (options.parameters)
target += "?" + HTTP.encodeFormData(options.parameters)
request.open("GET", target);
request.send(null);
};
20.3. Ajax
Ajax ,
HTTP XMLHttpRequest. (
XMLHttpRequest Ajax .) Ajax
Asynchronous JavaScript and XML ( JavaScript XML).1
(Jesse James Garrett)
2005 Ajax: A New Approach to
Web Applications (Ajax: ),
http://www.adaptivepath.com/publications/essays/archi'
ves/000385.php.
Ajax ,
.
, , ,
Ajax. JavaScript
. ,
XML , Ajax,
, . Ajax
HTTP, .
510
20. HTTP
XMLHttpRequest, Ajax,
Microsoft Netscape/Mozilla
, .1
2004 , Google
Gmail, XMLHttpRequest.
,
, , 2005 ,
Ajax.
Ajax
HTTP .
(
),
.
.
Ajax
XML
. 21 , XML
JavaScript, XPath XSL
XML HTML. Ajax
( XML)
(HTML, XSL)
XSLT. ,
, ,
.
Ajax RPC2.
Ajax
, ,
.
, RPC Ajax,
,
Ajax.
Ajax ,
, ,
:
Ajax
. , Ajax,
1
, XMLHttpRequest
. , XMLHttp
Request ,
. ,
HTTP,
.
RPC Remote Procedure Call (
) ,
.
20.3. Ajax
511
, . ,
,
.
.
20.3.1. Ajax
, ,
, XMLHttpRe
quest. ,
. , Ajax
, .
,
, Ajax.
20.8 ,
,
. ,
, ,
HTTP HEAD XMLHttpRequest.
,
, ,
(. 20.1).
,
, .
Tooltip, 16.4 (
, 17.3).
, Geometry 14.2
HTTP.getHeaders() 20.4.
: onload,
onmouseover,
XMLHttpRequest. .
. 20.1. Ajax
512
20. HTTP
20.8. Ajax
/**
* linkdetails.js
*
* ,
*
* .
* , ,
* , ,
* HTTP HEAD, XMLHttpRequest.
*
* Tooltip.js, HTTP.js Geometry.js
*/
(function() { // ,
//
var tooltip = new Tooltip();
// init()
if (window.addEventListener) window.addEventListener("load", init, false);
else if (window.attachEvent) window.attachEvent("onload", init);
//
function init() {
var links = document.getElementsByTagName('a');
//
for(var i = 0; i < links.length; i++)
if (links[i].href) addTooltipToLink(links[i]);
}
//
function addTooltipToLink(link) {
//
if (link.addEventListener) { //
link.addEventListener("mouseover", mouseover, false);
link.addEventListener("mouseout", mouseout, false);
}
else if (link.attachEvent) { // IE
link.attachEvent("onmouseover", mouseover);
link.attachEvent("onmouseout", mouseout);
}
var timer; // setTimeout/clearTimeout
function mouseover(event) {
var e = event || window.event;
// ,
//
var x = e.clientX + Geometry.getHorizontalScroll() + 25;
var y = e.clientY + Geometry.getVerticalScroll() + 15;
// ,
if (timer) window.clearTimeout(timer);
//
timer = window.setTimeout(showTooltip, 500);
20.3. Ajax
513
function showTooltip() {
// HTTP ,
// , XMLHttpRequest
// .
if (link.protocol == "http:" && link.host == location.host) {
//
HTTP.getHeaders(link.href, function(headers) {
//
var tip = "URL: " + link.href + "<br>" +
": " + headers["ContentType"] + "<br>" +
": " + headers["ContentLength"] + "<br>" +
": " + headers["LastModified"];
//
tooltip.show(tip, x, y);
});
}
else {
// , ,
// URL
tooltip.show("URL: " + link.href, x, y);
}
}
}
function mouseout(e) {
// ,
// , .
if (timer) window.clearTimeout(timer);
timer = null;
tooltip.hide();
}
}
})();
20.3.2.
(single'page application)
, : JavaScript
, .
.
DHTML,
.
XMLHttpRequest Ajax
.
.
, ,
JavaScript, ,
HTML,
. JavaScript
XMLHttpRequest JavaScript
, eval(). Java
514
20. HTTP
Script
XMLHttpRequest DHTML
.
20.3.3.
(remote scripting)
Ajax
: HTTP
( ) .
Apple, 2002 ,
, <iframe> HTTP
(http://developer.apple.com/internet/webcontent/iframe.html).
, HTML,
<script>, JavaScript
, , <iframe>.
JavaScript
.
20.3.4.
Ajax
, Ajax .
,
Ajax.
.
,
. ,
, ,
. , HTTP
XMLHttpRequest,
.
HTTP
. Ajax
(, DHTML;
. 16), XMLHttpRequest.
: 20.8
, HTTP
.
, ()
.
.
URL.
,
URL. Ajax
: Ajax HTTP
, URL .
20.3. Ajax
515
,
. ,
URL .
Google Maps
(http://local.google.com).
, URL
, , . Google
, link
to this page ( ). URL
URL. ,
,
. ,
: ,
, URL URL
.
, Ajax,
. HTTP,
, XMLHttpRequest,
.
. Ajax HTTP
,
.
, ,
, .
URL . , ,
,
,
.
, Ajax
,
HTTP.
, ,
,
. ,
,
.
, .
, HTTP
, , .
Google Maps .
, ,
, , ,
.
516
20. HTTP
Ajax
. ,
,
( XMLHttpRequest),
,
, .
. Ajax
/,
, ,
.
20.4. HTTP
<script>
Internet Explorer 5 6 XMLHttpRequest
ActiveX.
ActiveX Internet Explorer,
XMLHttpRequest.
HTTP GET
<iframe> <script>. ,
XMLHttpRequest,1
, , HTTP.getText(),
ActiveX.
HTTP src
<script> <iframe>.
. <iframe> ,
HTML. ,
, HTML. ,
Internet Explorer onload
onreadystatechange <iframe>, .
, , <script>
.
URL, ,
, .
URL, JavaScript
(, ) ,
.
<script>,
.
20.9 PHP.
1
XMLHttpRequest, , Java
.
517
20.9. jsquoter.php
<?php
// ,
header("ContentType: text/javascript");
// URL
$func = $_GET["func"];
// JavaSript
$filename = $_GET["url"];
// URL func
$lines = file($filename);
//
$text = implode("", $lines); //
//
$escaped = str_replace(array("'", "\"", "\n", "\r"),
array("\\'", "\\\"", "\\n", "\\r"),
$text);
// JavaScript
echo "$func('$escaped');"
?>
20.10 jsquo'
ter.php 20.9 HTTP.getText()
20.2.
20.10. HTTP.getTextWithScript()
HTTP.getTextWithScript = function(url, callback) {
// .
var script = document.createElement("script");
document.body.appendChild(script);
// .
var funcname = "func" + HTTP.getTextWithScript.counter++;
// ,
// . , ,
// .
HTTP.getTextWithScript[funcname] = function(text) {
//
callback(text);
// script .
document.body.removeChild(script);
delete HTTP.getTextWithScript[funcname];
}
// URL, ,
// jsquoter.php.
// src <script>, URL.
script.src = "jsquoter.php" +
"?url=" + encodeURIComponent(url) + "&func=" +
encodeURIComponent("HTTP.getTextWithScript." + funcname);
}
//
// ,
// .
HTTP.getTextWithScript.counter = 0;
JavaScript XML
,
Ajax, HTTP
XMLHttpRequest, 20. X
Ajax XML,
XML .
, XML
JavaScript.
XML: ,
XML' HTML.
XML
.
(API) W3C DOM, XML
XSL, XML
XPath XML
().
,
, . ,
HTML XML
DOM XPath. , JavaScript
,
XML.
, E4X
JavaScript, XML.
21.1. XML
20 , XMLHttpRequest
XML. responseXML
XMLHttpRequest Document,
21.1. XML*
519
XML. Document
XML. ,
XML, XML XML
HttpRequest, XML XML
XML.
JavaScript,
XML .
, Internet Explo
rer, Firefox.
XML (. 10).
,
. ,
, xml.js,
,
:
var XML = {};
21.1.1.
XML (
) Firefox docu
ment.implementation.createDocument() DOM Level 2. Internet
Explorer ActiveX MSXML2.DOMDocument.
21.1 XML.newDocument(),
.
XML ,
,
.
21.1. XML'
/**
* Document.
* . ,
* . ,
* URL, .
*/
XML.newDocument = function(rootTagName, namespaceURL) {
if (!rootTagName) rootTagName = "";
if (!namespaceURL) namespaceURL = "";
if (document.implementation && document.implementation.createDocument) {
// W3C
return document.implementation.createDocument(namespaceURL,
rootTagName, null);
}
else { // , IE
// ActiveX.
// ,
//
520
, .
,
(namespaceURL) {
if (!prefix) prefix = "a0"; // Firefox
}
else prefix = "";
// (
// )
var text = "<" + (prefix?(prefix+":"):"") + tagname +
(namespaceURL
?(" xmlns:" + prefix + '="' + namespaceURL +'"')
:"") +
"/>";
//
doc.loadXML(text);
}
return doc;
}
};
21.1.2.
20 , XMLHttpRequest
HTTP . XML
responseXML
DOM Document. , XMLHttpRequest
, , ,
XML.
. XML Document, ,
21.1, XML,
. 21.2 ,
. , IE , Mozilla,
.
21.2. XML'
/**
* XML URL
* Document
*/
21.1. XML*
521
XML.load = function(url) {
// ,
var xmldoc = XML.newDocument();
xmldoc.async = false; //
xmldoc.load(url);
//
return xmldoc;
//
};
XMLHttpRequest, load()
. XMLHttpRequest.
, XML, XMLHttpRequest
. ,
HTTP. ,
,
. , HTTP, load()
GET
POST.
XMLHttpRequest, load() .
, async
false. 21.3
XML.load().
21.3. XML'
/**
* XML URL.
* , .
* .
*/
XML.loadAsync = function(url, callback) {
var xmldoc = XML.newDocument();
// XML createDocument,
// onload ,
if (document.implementation && document.implementation.createDocument){
xmldoc.onload = function() { callback(xmldoc); };
}
// onreadystatechange,
// XMLHttpRequest
else {
xmldoc.onreadystatechange = function() {
if (xmldoc.readyState == 4) callback(xmldoc);
};
}
//
xmldoc.load(url);
};
21.1.3. XML
XML,
JavaScript, . ,
522
Mozilla, DOMParser, IE
loadXML() Document. (
XML.newDocument() 21.1, .)
21.4 ,
XML Mozilla,
IE. , ,
, XMLHttpRequest
URL data:.
21.4. XML'
/**
* XML,
* , Document.
*/
XML.parse = function(text) {
if (typeof DOMParser != "undefined") {
// Mozilla, Firefox
return (new DOMParser()).parseFromString(text, "application/xml");
}
else if (typeof ActiveXObject != "undefined") {
// Internet Explorer.
var doc = XML.newDocument(); //
doc.loadXML(text);
//
//
return doc;
//
}
else {
//
// URL data:
// Safari. (Manos Batsis)
// Sarissa (sarissa.sourceforge.net).
var url = "data:text/xml;charset=utf8," + encodeURIComponent(text);
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
return request.responseXML;
}
};
21.1.4. XML
Microsoft HTML <xml>,
XML
HTML. IE <xml>,
XML, document.getEle
mentById() DOM HTML. <xml>
src, , <xml>,
XML URL, .
XML
, HTML:
,
21.1. XML*
523
, . XML
. IE
, 21.5.
21.5. XML'
/**
* Document, <xml>
* . <xml> src,
* URL.
*
* ,
* .
*/
XML.getDataIsland = function(id) {
var doc;
//
doc = XML.getDataIsland.cache[id];
if (doc) return doc;
//
doc = document.getElementById(id);
// "src", URL
var url = doc.getAttribute('src');
if (url) {
doc = XML.load(url);
}
// , src , ,
// , <xml>. Internet Explorer
// doc .
// doc HTML,
//
else if (!doc.documentElement) {// ...
// , <xml>.
// <xml>, ,
//
var docelt = doc.firstChild;
while(docelt != null) {
if (docelt.nodeType == 1 /*Node.ELEMENT_NODE*/) break;
docelt = docelt.nextSibling;
}
//
doc = XML.newDocument();
// <xml> ,
if (docelt) doc.appendChild(doc.importNode(docelt, true));
}
//
XML.getDataIsland.cache[id] = doc;
return doc;
};
XML.getDataIsland.cache = {}; //
524
XML
, IE. HTML ,
(
). , XML,
<xml>. , ,
, .
CSS:
<style type="text/css">xml { display: none; }</style>
IE ,
HTML,
XML. , , 21.5
Firefox ( ,
), ,
, Firefox , HTML
. ,
. , ,
, XML
HTML. , XML
XSL ( XSL
), .
,
XML HTML,
XML <xml>,
XML
JavaScript,
, 21.4.
21.2. XML
c DOM API
XML
Document. Document W3C DOM API
HTMLDocument, do
cument .
HTML DOM XML DOM,
(API) DOM
XML
HTML.
525
. :
, Document
HTMLDocument, Element HTMLElement. HTMLDocument
HTMLElement XML Document Ele
ment. DOM
HTML, XML
, HTML.
, HTML XML DOM
getElementById(),
XML. DOM 1
HTML HTMLDocument. DOM Level 2
Document, .
XML getElementById()
, id.
id,
.
(Document Type Definition, DTD), DTD
DOCTYPE. XML, ,
, getElementById()
null. : getElementsByTagNa
me() Document Element XML. (
, XML
XPath; XPath
.)
HTML XML Document
body, <body> . XML
documentElement
. :
childNodes[] ,
, XML
DOCTYPE,
.
XML Element
HTMLElement, . HTML
DOM HTML HTMLEle
ment. , src <img> src HTMLI
mageElement, <img>. XML DOM
: Element tagName.
XML
getAttribute(), setAttribute() .
, ,
HTML, XML
. , id XML
, getElementById().
XML,
style. XML CSS,
class. HTML.
526
21.2.2. : HTML
XML
21.7 makeTable(),
XML DOM HTML DOM XML
HTML .
JavaScript, ,
XML
.
makeTable(),
. 21.6 XML,
( ).
21.6. XML
<?xml version="1.0"?>
<contacts>
<contact name="Able Baker"><email>able@example.com</email></contact>
<contact name="Careful Dodger"><email>dodger@example.com</email></contact>
<contact name="Eager Framer" personal="true">
<email>framer@example.com</email></contact>
</contacts>
HTML ,
makeTable() XML. :
schema .
<script>
// makeTable()
function displayAddressBook() {
var schema = {
rowtag: "contact",
columns: [
{ tagname: "@name", label: "Name" },
{ tagname: "email", label: "Address" }
]
};
var xmldoc = XML.load("addresses.xml"); // XML
makeTable(xmldoc, schema, "addresses"); // HTML
}
</script>
<button onclick="displayAddressBook()"> </button>
<div id="addresses"><! ></div>
makeTable() 21.7.
21.7. HTML' XML
/**
* XML HTML.
* HTML.
* ( element , ,
* .)
527
*
* schema JavaScript, ,
* . schema
* "rowtag", XML,
* . ,
* schema "columns", .
*
* .
* JavaScript. ,
* XML, ,
* . columns[] ,
* "tagname" "label".
* tagname XML,
* label .
* tagname @,
* , .
*/
function makeTable(xmldoc, schema, element) {
// <table>
var table = document.createElement("table");
// <th> <tr> <thead>
var thead = document.createElement("thead");
var header = document.createElement("tr");
for(var i = 0; i < schema.columns.length; i++) {
var c = schema.columns[i];
var label = (typeof c == "string")?c:c.label;
var cell = document.createElement("th");
cell.appendChild(document.createTextNode(label));
header.appendChild(cell);
}
//
thead.appendChild(header);
table.appendChild(thead);
// <tbody>
var tbody = document.createElement("tbody");
table.appendChild(tbody);
// XML,
var xmlrows = xmldoc.getElementsByTagName(schema.rowtag);
// . .
for(var r=0; r < xmlrows.length; r++) {
// XML
var xmlrow = xmlrows[r];
// HTML
var row = document.createElement("tr");
// , schema
for(var c = 0; c < schema.columns.length; c++) {
var sc = schema.columns[c];
var tagname = (typeof sc == "string")?sc:sc.tagname;
var celltext;
if (tagname.charAt(0) == '@') {
// tagname '@'
528
21.3. XML
XSLT
,
Document, XML,
, ,
XSLT. XSLT
XSL Transformations (XSL), XSL Extensible
Stylesheet Language ( ). XSL
XML, ,
XML. XSL
, 21.8 ,
HTML XML,
21.6.
21.8. XSL'
<?xml version="1.0"?><! XML >
<! xsl, xsl html >
<xsl:stylesheet version="1.0"
529
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<! , HTML >
<xsl:template match="/">
<table>
<tr><th></th><th> </th></tr>
<xsl:applytemplates/> <! >
</table>
</xsl:template>
<! <contact>... >
<xsl:template match="contact">
<tr> <! >
<! name contact >
<td><xsl:valueof select="@name"/></td>
<xsl:applytemplates/> <! >
</tr>
</xsl:template>
<!
<email>,
>
<xsl:template match="email">
<td><xsl:valueof select="."/></td>
</xsl:template>
</xsl:stylesheet>
: XSLT
, XML,
, . ,
. ,
JavaScript XSLT.
W3C XSLT
DOM Document Element. Mozilla
XSLT JavaScript
XSLTProcessor. IE XML Document Element transform
530
Node(), . 21.9
. XML.Trans
former, XSL
XML. transform()
XML.Transformer
XML,
DOM .
21.9. XSLT Mozilla Internet Explorer
/**
* XML.Transformer XSL.
* stylesheet URL,
* . ,
* DOM Document.
*/
XML.Transformer = function(stylesheet) {
// , .
if (typeof stylesheet == "string") stylesheet = XML.load(stylesheet);
this.stylesheet = stylesheet;
// Mozilla XSLTProcessor
// .
if (typeof XSLTProcessor != "undefined") {
this.processor = new XSLTProcessor();
this.processor.importStylesheet(this.stylesheet);
}
};
/**
* transform() XML.Transformer.
* xml
* .
* , HTML,
* .
*/
XML.Transformer.prototype.transform = function(node, element) {
// id, .
if (typeof element == "string") element = document.getElementById(element);
if (this.processor) {
// XSLTProcessor ( Mozilla),
// .
// DOM DocumentFragment.
var fragment = this.processor.transformToFragment(node, document);
// .
element.innerHTML = "";
// .
element.appendChild(fragment);
}
else if ("transformNode" in node) {
// transformNode() ( IE), .
// : transformNode() .
element.innerHTML = node.transformNode(this.stylesheet);
}
531
else {
// .
throw "XSLT ";
}
};
/**
* , XSLT,
* , .
*/
XML.transform = function(xmldoc, stylesheet, element) {
var transformer = new XML.Transformer(stylesheet);
transformer.transform(xmldoc, element);
}
IE Mozilla
, API XSLT.
,
AJAXSLT JavaScript
XSLT. AJAXSLT
Google, http://goog'
ajaxslt.sourceforge.net.
21.4. XML
XPath
XPath , ,
XML. XPath
XML
( ).
XPath ,
21.4.1 XPath,
, , XPath.
W3C API
DOM XPath. Firefox
evaluate()
Document ( HTML, XML). ,
Mozilla Document.createExpression(),
XPath ,
.
IE XPath select
SingleNode() selectNodes() XML ( HTML) Document Ele
ment. ,
: W3C, IE.
XPath ,
AJAXSLT
(http://goog'ajaxslt.sourceforge.net).
532
21.4.1. XPath
DOM ,
XPath .
, , XPath
. XPath
:
contact // <contact>,
contact[1] // <contact>,
contact[last()] // <contact>
contact[last()1] // <contact>
: XPath
1, 0, JavaScript.
path () XPath ,
XML
/. :
contact/email // <email> <contact>
/contacts // <contacts> ( )
contact[1]/email // <email> <contact>
contact/email[2] // <email> <contact>
: contact/email[2]
<email>, <email> <contact>,
. , contact[2]/email
(contact/email)[2].
(.) XPath ,
(//)
, . :
.//email // <email>
//email // <email> ( )
XPath XML,
.
@:
@id // id
contact/@name // name <contact>
, XPath
, XML. :
contact[@personal="true"] // <contact> personal="true"
XML
text():
contact/email/text() // <email>
//text() //
XPath ,
:
//xsl:template // <xsl:template>
533
, XPath,
,
URL.
XPath. XPath ,
. count(),
, :
count(//email) // <email>
21.4.2. XPath
21.10 XML.XPathExpression,
IE, , ,
Firefox.
21.10. XPath'
/**
* XML.XPathExpression , XPath
* URL.
* XML.XPathExpression ,
* (
* ) getNode() getNodes().
*
* XPath.
*
* XML,
* JavaScript,
* URL,
* . ,
* URL.
*/
XML.XPathExpression = function(xpathText, namespaces) {
this.xpathText = xpathText; //
this.namespaces = namespaces; //
if (document.createExpression) {
// W3C , W3C API
// XPath
this.xpathExpr =
document.createExpression(xpathText,
//
// , URL.
function(prefix) {
return namespaces[prefix];
});
}
else {
// , IE
// , IE
this.namespaceString = "";
if (namespaces != null) {
for(var prefix in namespaces) {
534
};
/**
* getNodes() XML.XPathExpression. XPath
* . context Document
* Element. , ,
* , .
*/
XML.XPathExpression.prototype.getNodes = function(context) {
if (this.xpathExpr) {
// W3C , ,
// .
// .
var result =
this.xpathExpr.evaluate(context,
//
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null);
// .
var a = new Array(result.snapshotLength);
for(var i = 0; i < result.snapshotLength; i++) {
a[i] = result.snapshotItem(i);
}
return a;
}
else {
// W3C ,
// IE API.
try {
// , Document
var doc = context.ownerDocument;
// ownerDocument, ,
// Document
if (doc == null) doc = context;
// URL, IE
doc.setProperty("SelectionLanguage", "XPath");
doc.setProperty("SelectionNamespaces", this.namespaceString);
// IE Document Element,
// , ,
// documentElement
if (context == doc) context = doc.documentElement;
// IE selectNodes()
return context.selectNodes(this.xpathText);
}
catch(e) {
535
// IE API , ,
throw "XPath .";
}
}
}
/**
* getNode() XML.XPathExpression. XPath
* ,
* ( null, ).
* , .
* getNodes()
* .
*/
XML.XPathExpression.prototype.getNode = function(context) {
if (this.xpathExpr) {
var result =
this.xpathExpr.evaluate(context,
//
XPathResult.FIRST_ORDERED_NODE_TYPE,
null);
return result.singleNodeValue;
}
else {
try {
var doc = context.ownerDocument;
if (doc == null) doc = context;
doc.setProperty("SelectionLanguage", "XPath");
doc.setProperty("SelectionNamespaces", this.namespaceString);
if (context == doc) context = doc.documentElement;
// IE, selectNodes, selectSingleNode
return context.selectSingleNode(this.xpathText);
}
catch(e) {
throw "XPath .";
}
}
};
// , XML.XPathExpression
// getNodes()
XML.getNodes = function(context, xpathExpr, namespaces) {
return (new XML.XPathExpression(xpathExpr, namespaces)).getNodes(context);
};
// , XML.XPathExpression
// getNode()
XML.getNode = function(context, xpathExpr, namespaces) {
return (new XML.XPathExpression(xpathExpr, namespaces)).getNode(context);
};
536
. IE XPath
, .
W3C , , :
// <p>
var n = document.evaluate("count(//p)", document, null,
XPathResult.NUMBER_TYPE, null).numberValue;
//
var text = document.evaluate("//p[2]/text()", document, null,
XPathResult.STRING_TYPE, null).stringValue;
. ,
XPath
document.evaluate(). 21.10
document.createExpression(), XPath
,
. , , HTML
<p> document. Firefox XPath
XML, HTML.
W3C XPath API
, Document, XPathExpression XPathResult.
21.5. XML
XML (
), . ,
, XML HTTP POST,
XMLHttpRequest. XML
!
Mozilla
XMLSerializer. IE : xml XML Document
Element,
.
21.11 ,
Mozilla IE.
21.11. XML'
/**
* XML XML .
*/
XML.serialize = function(node) {
if (typeof XMLSerializer != "undefined")
return (new XMLSerializer()).serializeToString(node);
else if (node.xml) return node.xml;
else throw "XML.serialize " + node;
};
537
21.6. HTML
XML
XML ,
, HTML
. HTML IE
datasrc datafld ( fld field ).
XML,
, XPath DOM
,
IE Firefox. HTML datasource.
XML
URL XML. ,
foreach, XPath,
XML, .
XML, foreach, HTML
.
,
data. XPath,
, foreach. data
XML.getNode(), , ,
HTML, .
.
21.12 HTML,
XML .
onload.
21.12. XML' HTML'
<html>
<! XML >
<head><script src="xml.js"></script></head>
<! >
<body onload="XML.expandTemplates()">
<! XML >
<xml id="data" style="display:none"> <! CSS >
<contacts>
<contact name="Able Baker"><email>able@example.com</email></contact>
<contact name="Careful Dodger"><email>dodger@example.com</email></contact>
<contact name="Eager Framer"><email>framer@example.com</email></contact>
</contacts>
</xml>
<! HTML >
<table>
<tr><th></th><th></th></tr>
<! . id="data". >
<! <contact> >
<tr datasource="#data" foreach="//contact">
538
21.12 onload,
XML.expandTemplates().
21.13. ,
, DOMLevel 1
XML.getNode() XML.getNodes(), 21.10
XPath.
21.13. HTML'
/*
* , e.
* XPath ,
*
* URL, XML.XPathExpression()
*
* e , document.body.
* onload.
* .
*/
XML.expandTemplates = function(e, namespaces) {
// .
if (!e) e = document.body;
else if (typeof e == "string") e = document.getElementById(e);
if (!namespaces) namespaces = null; // undefined
//
//
//
if
HTML , "datasource".
.
: .
(e.getAttribute("datasource")) {
// .
XML.expandTemplate(e, namespaces);
}
else {
// .
// , ,
// .
var kids = []; //
for(var i = 0; i < e.childNodes.length; i++) {
var c = e.childNodes[i];
if (c.nodeType == 1) kids.push(e.childNodes[i]);
}
//
for(var i = 0; i < kids.length; i++)
XML.expandTemplates(kids[i], namespaces);
}
e,
data.
XPath datanode.
XPath
539
540
};
21.7. XML
XML, SOAP
,
XML. ,
XMLHttpRequest XPath SOAP .
JavaScript 21.14 XML,
SOAP, XMLHttpRequest
. ( .)
XPath SOAP, ,
.
,
. , SOAP
21.7. XML *
541
, SOAP
SOAP XML. ,
(Web Servi
ces Definition Language, WSDL) .
, .
.
JavaScript
(. 13.8.2). ,
,
. , Java
Script, , ,
, , ,
. JavaScript
HTML ,
Java
Script
.
21.14 IE,
. ,
,
.
.
( ) .
.
21.14 Firefox,
Firefox enablePrivilege().
,
.
file: URL, ,
(
, ).
, ,
.
21.14. ' SOAP
/**
* .
* SOAP
* , XMethods (http://www.xmethods.net).
* .
* .
* , XMethod .
* . : http://www.xmethods.net/v2/demoguidelines.html
*/
function getExchangeRate(country1, country2) {
// Firefox
542
.
, ,
. UniversalXPConnect
XMLHttpRequest,
UniversalBrowserRead .
IE
"" " "
> >>.
(typeof netscape != "undefined") {
netscape.security.PrivilegeManager.
enablePrivilege("UniversalXPConnect UniversalBrowserRead");
}
// XMLHttpRequest SOAP.
// .
var request = HTTP.newRequest();
// POST
request.open("POST", "http://services.xmethods.net/soap", false);
// : POST XML
request.setRequestHeader("ContentType", "text/xml");
// SOAP
request.setRequestHeader("SOAPAction", '""');
// SOAP
request.send(
'<?xml version="1.0" encoding="UTF8"?>' +
'<soap:Envelope' +
' xmlns:ex="urn:xmethodsCurrencyExchange"' +
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
' xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"' +
' xmlns:xs="http://www.w3.org/2001/XMLSchema"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance">' +
' <soap:Body ' +
' soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
' <ex:getRate>' +
' <country1 xsi:type="xs:string">' + country1 + '</country1>' +
' <country2 xsi:type="xs:string">' + country2 + '</country2>' +
' </ex:getRate>' +
' </soap:Body>' +
'</soap:Envelope>'
);
// HTTP ,
if (request.status != 200) throw request.statusText;
// XPath <getRateResponse>
var query = "/s:Envelope/s:Body/ex:getRateResponse";
// ,
var namespaceMapping = {
s: "http://schemas.xmlsoap.org/soap/envelope/", // SOAP
ex: "urn:xmethodsCurrencyExchange" // ,
};
543
// <getRateResponse>
var responseNode=XML.getNode(request.responseXML, query,
namespaceMapping);
// <Result>
// <getRateReponse>
return responseNode.firstChild.firstChild.nodeValue;
}
E4X
, JavaScript
XML. , XML
, :
pt = <periodictable></periodictable>;
//
var elements = ["", "", ""]; //
// XML,
1
E4X ECMA357.
http://www.ecmainternational.org/publications/stan'
dards/Ecma'357.htm.
544
XML.
:
pt.element += new XML('<element id="5"><name></name></element>');
XML XML()
XMLList():
pt.element += new XMLList('<element id="6"><name>Carbon</name></element>' +
'<element id="7"><name>Nitrogen</name></element>');
XML ,
E4X:
var elements = pt.element; // <element>
var names = pt.element.name; // <name>
var n = names[0];
// "": <name>.
E4X XML
. (..) ;
(.):
// <name>
var names2 = pt..name;
E4X :
// <element>.
// <name>.
var names3 = pt.element.*;
E4X @ (
XPath). ,
:
//
var atomicNumber = pt.element[1].@id;
(@*):
// <element>
var atomicNums = pt.element.@*;
:
// ,
// , id < 3
var lightElements = pt.element.(@id < 3);
// <element> ,
// , "".
// <name> <element>.
var bElementNames = pt.element.(name.charAt(0) == '').name;
545
E4X XML
. for/each/in for/in,
:
//
// (, print().)
for each (var e in pt.element) {
print(e.name);
}
//
for each (var n in pt.element.@*) print(n);
, E4X, for/each/in
.
E4X .
:
// <element>
// , :
//
// <element id="1" symbol="H">
// <name></name>
// <weight>1.00794</weight>
// </element>
//
pt.element[0].@symbol = "H";
pt.element[0].weight = 1.00794;
delete
:
delete pt.element[0].@symbol; //
delete pt..weight;
// <weight>
E4X ,
XML
. , E4X XML.
insertChildBefore():
pt.insertChildBefore(pt.element[1],
<element id="1"><name></name></element>);
: , E4X,
XML. DOM Node Element,
, DOM API. E4X XML
domNode(), DOM Node, XML,
Firefox 1.5 . E4X ,
DOM Node XML() E4X
DOM. Firefox 1.5,
E4X JavaScript.
E4X
API XML.
.
, JavaScript
.
, (
). ,
. Java
Script CSS
,
, .
,
.
:
, ,
, ,
.
. (
),
.
Ajax,
, .
,
JavaScript :
22.1.
547
.
SVG XML,
JavaScript.
Flash
.
Flash 6, 8
JavaScript.
, Java
Sun Microsystems.
12 23, JavaScript Java
, Mozilla Java
. Java JavaScript
Java
.
, .
22.1.
HTML
<img>. HTML, <img> DOM
, .
.
548
22.
, <img>
name, Image
:
document.images.nextpage
document.images["nextpage"]
name,
Image document:
document.nextpage
22.1.2.
Image , src
, . ,
URL, . ,
src
.
HTML
,
,
.
, . (
, ,
.) ,
,
.1
HTML <a>
onmouseover onmouseout :
<a href="help.html"
onmouseover="document.helpimage.src='images/help_rollover.gif';"
onmouseout="document.helpimage.src='images/help.gif';">
<img name="helpimage" src="images/help.gif" border="0">
</a>
: <img> name,
Image <a>.
border
.
<a>: , src URL
. ,
1
, ,
CSS :hover,
CSS ,
. ,
CSS , .
:hover
, .
22.1.
549
,
<a>, <a>.
<img>, Image.
Image this:
<img src="images/help.gif"
onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">
, <img> <a>
onclick.
22.1.3.
,
. ,
,
. ,
Image Imange(). ,
src URL, .
, ,
. , URL
, ,
.
, ,
,
,
, .
, :
<script>(new Image()).src = "images/help_rollover.gif";</script>
<img src="images/help.gif"
onmouseover="this.src='images/help_rollover.gif'"
onmouseout="this.src='images/help.gif'">
22.1.4.
<script>
JavaScript,
. Java
Script. (HTML)
(JavaScript) ,
, . , JavaScript
HTML. 22.1 ,
<img>.
22.1.
/**
* <img>,
* , URL .
550
22.
*
* img ,
* id name.
*
* onmouseover
* onmouseout , ,
* .
*/
function addRollover(img, rolloverURL) {
if (typeof img == "string") { // img ,
var id = img;
// , id, Image
img = null;
// .
// , id
if (document.getElementById) img = document.getElementById(id);
else if (document.all) img = document.all[id];
// id ,
// name.
if (!img) img = document.images[id];
// ,
if (!img) return;
}
// , <img>,
if (img.tagName.toLowerCase() != "img") return;
// URL
var baseURL = img.src;
//
(new Image()).src = rolloverURL;
img.onmouseover = function() { img.src = rolloverURL; }
img.onmouseout = function() { img.src = baseURL; }
}
addRollover(), 22.1, ,
HTML
, .
JavaScript ,
, URL .
<img> . ,
:
<img src="normalImage.gif" rollover="rolloverImage.gif">
,
, ,
initRollovers()
22.2.
22.2.
/**
* <img> , "rollover".
22.1.
551
* URL ,
* , ;
* ,
* .
*/
function initRollovers() {
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
var rolloverURL = image.getAttribute("rollover");
if (rolloverURL) addRollover(image, rolloverURL);
}
}
, , initRollovers()
.
:
if (window.addEventListener)
window.addEventListener("load", initRollovers, false);
else if (window.attachEvent)
window.attachEvent("onload", initRollovers);
onload 17.
: addRollover() initRollovers()
,
,
. ,
,
<script src=> rollover <img>.
HTML
, rollover
<img>, XHTML
XML. 22.3 initRollovers(),
. ,
Internet Explorer 6,
DOM, .
22.3.
XHTML
/**
* <img> , "ro:src".
* URL , ,
* ,
* , .
* ro: URI
* "http://www.davidflanagan.com/rollover"
*/
function initRollovers() {
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
552
22.
var rolloverURL = image.getAttributeNS(initRollovers.xmlns, "src");
if (rolloverURL) addRollover(image, rolloverURL);
}
}
// URI "ro:"
initRollovers.xmlns = "http://www.davidflanagan.com/rollover";
22.1.5.
src <img>
; ,
.
,
.
22.4 ImageLoop,
.
src ,
22.1. onload Im
age, (,
, ). , ,
Window.setInterval(),
: src
<img> URL .
HTML, ImageLoop:
<head>
<script src="ImageLoop.js"></script>
<script>
var animation =
new ImageLoop("loop", 5,["images/0.gif", "images/1.gif", "images/2.gif",
"images/3.gif", "images/4.gif", "images/5.gif",
"images/6.gif", "images/7.gif", "images/8.gif"]);
</script>
</head>
<body>
<img id="loop" src="images/loading.gif">
<button onclick="animation.start()">Start</button>
<button onclick="animation.stop()">Stop</button>
</body>
22.4 ,
, Image.onload
Window.setInterval() , .
ImageLoop()
, , ImageLoop.
22.4.
/**
* ImageLoop.js: ImageLoop
*
* :
22.1.
* imageId: <img>,
* fps:
* frameURLs: URL,
*
* :
* start(): ( , )
* stop():
*
* :
* loaded: true , false
*/
function ImageLoop(imageId, fps, frameURLs) {
// id . ,
// , .
this.imageId = imageId;
//
this.frameInterval = 1000/fps;
// , Image
this.frames = new Array(frameURLs.length);
this.image = null;
this.loaded = false;
this.loadedFrames = 0;
this.startOnLoad = false;
this.frameNumber = 1;
this.timer = null;
//
//
//
//
//
//
<img>, id
?
setInterval()
// frames[]
for(var i = 0; i < frameURLs.length; i++) {
this.frames[i] = new Image( );
// Image
// , ,
//
this.frames[i].onload = countLoadedFrames; //
this.frames[i].src = frameURLs[i];
//
}
// ,
// . ,
// .
var loop = this;
function countLoadedFrames() {
loop.loadedFrames++;
if (loop.loadedFrames == loop.frames.length) {
loop.loaded = true;
if (loop.startOnLoad) loop.start();
}
}
// , .
// , . . setInterval()
// , .
// , ImageLoop
this._displayNextFrame = function() {
// . (%)
//
553
554
22.
loop.frameNumber = (loop.frameNumber+1)%loop.frames.length;
// src URL
loop.image.src = loop.frames[loop.frameNumber].src;
};
}
/**
* ImageLoop.
* , ,
*
*/
ImageLoop.prototype.start = function() {
if (this.timer != null) return; //
// ,
if (!this.loaded) this.startOnLoad = true;
else {
// <img> id,
if (!this.image) this.image = document.getElementById(this.imageId);
//
this._displayNextFrame();
//
this.timer = setInterval(this._displayNextFrame, this.frameInterval);
}
};
/** ImageLoop */
ImageLoop.prototype.stop = function() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
};
22.1.6.
onload,
22.4, Image .
onerror ,
, URL .
onabort ,
(, ) ,
. ( )
.
Image complete.
false, ; true,
. , complete
true ,
.
Image
<img>. ,
, JavaScript
,
.
22.2. CSS
555
22.2. CSS
16, ,
CSS DHTML.
: backgroundcolor
, border
. , , borderleft bordertop,
,
. ,
, !
,
,
. 22.1 22.2. ,
.
. 22.1. , CSS
. 22.2. , CSS
556
22.
22.2.1. CSS
, . 22.1,
HTML:
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<! DOCTYPE IE >
<html>
<head>
<script src="BarChart.js"></script> <! >
<script>
function drawChart() {
var chart = makeBarChart([1,2,4,8,16,32,64,128,256], 600, 300);
var container = document.getElementById("chartContainer");
container.appendChild(chart);
}
</script>
</head>
<body onload="drawChart( )">
<h2>y = 2<sup>n</sup></h2><! >
<div id="chartContainer"><! ></div>
<! >
<i> :
</i>
</body>
</html>
, make
BarChar() BarChart.js, 22.5.
22.5. CSS
/**
* BarChart.js:
* makeBarChart(),
* data[].
*
* width height, ,
* . barcolor
* .
* <div>, ,
* , , .
* ,
* .
**/
function makeBarChart(data, width, height, barcolor) {
//
if (!width) width = 500;
if (!height) height = 350;
if (!barcolor) barcolor = "blue";
// width height .
// ,
// .
557
22.2. CSS
width = 24; // 10px 2px
height = 14; // 10px 2px
// . :
// , . .
//
// ,
// .
var chart = document.createElement("div");
chart.style.position = "relative";
//
chart.style.width = width + "px";
//
chart.style.height = height + "px";
//
chart.style.border = "solid black 2px"; //
chart.style.paddingLeft = "10px";
//
chart.style.paddingRight = "10px";
//
chart.style.paddingTop = "10px";
//
chart.style.paddingBottom = "0px";
//
chart.style.backgroundColor = "white"; //
//
var barwidth = Math.floor(width/data.length);
// data[].
// Function.apply().
var maxdata = Math.max.apply(this, data);
// : scale*data[i]
var scale = height/maxdata;
//
for(var i = 0; i < data.length; i++) {
var bar = document.createElement("div");
var barheight = data[i] * scale;
bar.style.position = "absolute";
bar.style.left = (barwidth*i+1+10)+"px";
//
//
//
//
//
bar.style.top = heightbarheight+10+"px";//
//
bar.style.width = (barwidth2) + "px"; //
bar.style.height = (barheight1) + "px"; //
bar.style.border = "solid black 1px";
//
bar.style.backgroundColor = barcolor;
//
bar.style.fontSize = "0px";
//
chart.appendChild(bar);
//
//
2
1
IE
}
//
return chart;
}
22.5
. <div>
15.
, CSS
, 16.
, ,
558
22.
. CSS
border backgroundcolor.
position:relative top left
.
,
.
( ) ,
.
22.5
.
, ,
.
22.2.2. CSSDrawing
, 22.5,
. CSS
, , . 22.2,
, ,
.
22.6 CSSDrawing,
,
22.7 , CSSDrawing
, . 22.2.
22.6. CSSDrawing
/**
* div, CSS
* .
* .
*
* :
*
* new CSSDrawing(x, y, width, height, classname, id)
*
* <div> position:absolute
* .
*
* width height:
*
* new CSSDrawing(width, height, classname, id)
*
* <div>
* position:relative ( , ,
* ,
* ).
*
* classname id .
* ,
22.2. CSS
* class id <div>
* , CSS .
*/
function CSSDrawing(/* */) {
// <div>,
var d = this.div = document.createElement("div");
var next;
// ,
// div
if (arguments.length >= 4 && typeof arguments[3] == "number") {
d.style.position = "absolute";
d.style.left = arguments[0] + "px";
d.style.top = arguments[1] + "px";
d.style.width = arguments[2] + "px";
d.style.height = arguments[3] + "px";
next = 4;
}
else {
d.style.position = "relative"; //
d.style.width = arguments[0] + "px";
d.style.height = arguments[1] + "px";
next = 2;
}
// class id, .
if (arguments[next]) d.className = arguments[next];
if (arguments[next+1]) d.id = arguments[next+1];
}
/**
* .
*
* x, y, w, h:
.
* content:
HTML,
* classname, id: class id .
*
,
*
, .
* : <div>,
*/
CSSDrawing.prototype.box = function(x, y, w, h, content, classname, id) {
var d = document.createElement("div");
if (classname) d.className = classname;
if (id) d.id = id;
d.style.position = "absolute";
d.style.left = x + "px";
d.style.top = y + "px";
d.style.width = w + "px";
d.style.height = h + "px";
d.innerHTML = content;
this.div.appendChild(d);
return d;
};
/**
559
560
22.
* .
*
* x, y, width:
* classname, id: class id.
*
, ,
*
,
*
, .
* : <div>,
*/
CSSDrawing.prototype.horizontal = function(x, y, width, classname, id) {
var d = document.createElement("div");
if (classname) d.className = classname;
if (id) d.id = id;
d.style.position = "absolute";
d.style.left = x + "px";
d.style.top = y + "px";
d.style.width = width + "px";
d.style.height = 1 + "px";
d.style.borderLeftWidth = d.style.borderRightWidth =
d.style.borderBottomWidth = "0px";
this.div.appendChild(d);
return d;
};
/**
* .
* horizontal().
*/
CSSDrawing.prototype.vertical = function(x, y, height, classname, id) {
var d = document.createElement("div");
if (classname) d.className = classname;
if (id) d.id = id;
d.style.position = "absolute";
d.style.left = x + "px";
d.style.top = y + "px";
d.style.width = 1 + "px";
d.style.height = height + "px";
d.style.borderRightWidth = d.style.borderBottomWidth =
d.style.borderTopWidth = "0px";
this.div.appendChild(d);
return d;
};
/** */
CSSDrawing.prototype.insert = function(container) {
if (typeof container == "string")
container = document.getElementById(container);
container.appendChild(this.div);
}
/** , */
CSSDrawing.prototype.replace = function(elt) {
if (typeof elt == "string") elt = document.getElementById(elt);
elt.parentNode.replaceChild(this.div, elt);
}
22.2. CSS
561
CSSDrawing() CSSDrawing,
<div>. box(), vertical()
horizontal() CSS ,
.
,
class id . class
id CSS,
, . CSSDraw
ing , .
insert() replace().
22.7 CSSDrawing.
JavaScript drawFigure(), CSS
.
,
. ,
JavaScript CSS: drawFigure()
, .
,
CSSDrawing.
22.7. CSSDrawing
<!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<! DOCTYPE IE >
<html>
<head>
<script src="CSSDrawing.js"></script> <! >
<style>
/* */
.figure { border: solid black 2px; backgroundcolor: #eee;}
/* */
.grid { border: dotted black 1px; opacity: .1; }
/* */
.boxstyle {
border: solid black 2px;
background: #aaa;
padding: 2px 10px 2px 10px;
font: bold 12pt sansserif;
textalign: center;
}
/* , */
.boldline { border: solid black 2px; }
</style>
<script>
// dx,dy
function drawGrid(drawing, x, y, w, h, dx, dy) {
for(var x0 = x; x0 < x +w; x0 += dx)
drawing.vertical(x0, y, h, "grid");
for(var y0 = y; y0 < y + h; y0 += dy)
drawing.horizontal(x, y0, w, "grid");
562
22.
}
function drawFigure( ) {
//
var figure = new CSSDrawing(500, 200, "figure");
//
drawGrid(figure, 0, 0, 500, 200, 25, 25);
//
figure.box(200, 50, 75, 25, "Life", "boxstyle"); //
figure.box(50, 125, 75, 25, "Archaea", "boxstyle"); // 3
figure.box(200, 125, 75, 25, "Bacteria", "boxstyle"); // ..
figure.box(350, 125, 75, 25, "Eukaryota", "boxstyle"); // ..
// ,
// "Life". y : 50+25+2+2+2+2,
// y + height + top border + top padding + bottom padding + bottom border
// :
// , . .
figure.vertical(250, 83, 20, "boldline");
figure.horizontal(100, 103, 300, "boldline");
figure.vertical(100, 103, 22, "boldline");
figure.vertical(250, 103, 22, "boldline");
figure.vertical(400, 103, 22, "boldline");
//
//
//
//
"archaea"
"bacteria"
"eukaryota"
// ,
figure.replace("placeholder");
}
</script>
</head>
<body onload="drawFigure()">
<div id="placeholder"></div>
</body>
</html>
22.3. SVG
(SVG) XML
.
, GIF,
JPEG PNG, . SVG
, (
) , ,
. SVG :
<! >
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1000 1000"> <! >
<defs>
<! >
<linearGradient id="fade"> <! "fade" >
<stop offset="0%" stopcolor="#008"/> <! >
<stop offset="100%" stopcolor="#ccf"/><! >
</linearGradient>
</defs>
22.3. SVG
563
. 22.3. SVG
<!
>
<rect x="100" y="200" width="800" height="600"
stroke="black" strokewidth="25" fill="url(#fade)"/>
</svg>
. 22.3 SVG.
SVG .
, . SVG Java
Script CSS,
. ,
JavaScript ( HTML, SVG)
SVG.
SVG
SVG. ,
, W3C
http://www.w3.org/TR/SVG/. :
(DOM) SVG.
SVG XML
DOM, SVG DOM .
Firefox 1.5
SVG.
SVG, URL
. SVG XHTML,
:
<?xml version="1.0"?>
<!
HTML , SVG "svg:"
>
564
22.
22.3. SVG
565
,
.)
22.8. JavaScript SVG
/**
* <svg>.
* :
* canvas: SVG ( id )
* data: ,
* cx, cy, r:
* colors: HTML ,
* labels: ,
* lx, ly:
*/
function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
// "", id
if (typeof canvas == "string") canvas = document.getElementById(canvas);
// ,
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
// . .
var angles = []
for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
// .
startangle = 0;
for(var i = 0; i < data.length; i++) {
// ,
var endangle = startangle + angles[i];
//
// .
// 0
// ,
// .
var x1 = cx + r * Math.sin(startangle);
var y1 = cy r * Math.cos(startangle);
var x2 = cx + r * Math.sin(endangle);
var y2 = cy r * Math.cos(endangle);
// ,
var big = 0;
if (endangle startangle > Math.PI) big = 1;
// <svg:path>
// , createElementNS()
var path = document.createElementNS(SVG.ns, "path");
//
var d = "M " + cx + "," + cy + //
" L " + x1 + "," + y1 +
//
" A " + r + "," + r +
//
" 0 " + big + " 1 " +
//
x2 + "," + y2 +
//
,
(x1,y1)
r
...
(x2,y2)
566
22.
" Z";
// (cx,cy)
// XML,
// setAttribute().
// JavaScript
path.setAttribute("d", d);
//
path.setAttribute("fill", colors[i]); //
path.setAttribute("stroke", "black"); //
path.setAttribute("strokewidth", "2"); // 2
canvas.appendChild(path);
// ""
// ,
startangle = endangle;
//
var icon = document.createElementNS(SVG.ns, "rect");
icon.setAttribute("x", lx);
//
icon.setAttribute("y", ly + 30*i);
icon.setAttribute("width", 20);
//
icon.setAttribute("height", 20);
icon.setAttribute("fill", colors[i]); // ,
icon.setAttribute("stroke", "black"); //
icon.setAttribute("strokewidth", "2");
canvas.appendChild(icon);
// ""
//
var label = document.createElementNS(SVG.ns, "text");
label.setAttribute("x", lx + 30);
//
label.setAttribute("y", ly + 30*i + 18);
// CSS
label.setAttribute("fontfamily", "sansserif");
label.setAttribute("fontsize", "16");
// DOM <svg:text>
label.appendChild(document.createTextNode(labels[i]));
canvas.appendChild(label);
// ""
}
};
22.8 .
.
, SVG
. : SVG
, createElement() createElementNS().
SVG.ns 22.9.
,
. <svg:path>.
SVG ,
. <svg:path>
d.
, , . ,
M move to ( ),
X Y . L line to (
); ,
22.3. SVG
567
. , A,
(arc). ,
. ,
, http://www.w3.org/TR/SVG/.
22.8 SVG.ns,
SVG.
SVG.js, 22.9.
22.9. SVG'
//
var SVG = {};
// URL , SVG
SVG.ns = "http://www.w3.org/2000/svg";
SVG.xlinkns = "http://www.w3.org/1999/xlink";
// <svg>.
// : .
// , ,
// .
SVG.makeCanvas = function(id, pixelWidth, pixelHeight, userWidth, userHeight) {
var svg = document.createElementNS(SVG.ns, "svg:svg");
svg.setAttribute("id", id);
// ""
svg.setAttribute("width", pixelWidth);
svg.setAttribute("height", pixelHeight);
// ,
svg.setAttribute("viewBox", "0 0 " + userWidth + " " + userHeight);
// XLink, SVG
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink",
SVG.xlinkns);
return svg;
};
// ""
// data: URL <object>.
// SVG , URL
// data: SVG.
SVG.makeDataURL = function(canvas) {
// IE,
// URL data:
var text = (new XMLSerializer()).serializeToString(canvas);
var encodedText = encodeURIComponent(text);
return "data:image/svg+xml," + encodedText;
};
// <object> SVG
// URL data:
SVG.makeObjectTag = function(canvas, width, height) {
var object = document.createElement("object"); // <object>
object.width = width;
//
object.height = height;
object.data = SVG.makeDataURL(canvas);
// SVG URL
// data:
568
22.
object.type = "image/svg+xml"
return object;
// MIME SVG
SVG.makeCanvas().
DOM <svg>,
SVG. makeCanvas()
SVG ( ),
( ),
. (,
10001000 250250,
.)
createCanvas() <svg>, .
.
22.9
SVG .
SVG.makeDataURL() XML <svg> URL
data:. SVG.makeObjectTag()
<object> SVG,
SVG.makeDataURL(),
data . SVG.makeCanvas(), SVG.makeObjectTag()
<object>, .
SVG.makeObjectTag() ,
URL data: ( Firefox 1.0) DOM,
( document.createElementNS()),
SVG.
: IE, IE URL
data:, createElementNS(). SVG
IE DOM
, SVG.
URL javascript:
data:.
HTML,
pieChart() 22.8 SVG 22.9.
SVG,
<object>:
<script src="SVG.js"></script> <! >
<script src="svgpiechart.js"></script> <! >
<script>
function init() {
// <svg> 600x400 300x200
var canvas = SVG.makeCanvas("canvas", 300, 200, 600, 400);
pieChart(canvas, [12, 23, 34, 45], 200, 200, 150, // , ,
["red", "blue", "yellow", "green"], //
["","","",""], 400, 100); //
// :
document.body.appendChild(canvas);
22.4. VML
569
// <object>
var object = SVG.makeObjectTag(canvas, 300, 200);
document.body.appendChild(object);
}
// ,
window.onload = init;
</script>
22.4. VML
VML Microsoft SVG. SVG, VML
XML,
. VML SVG. ,
VML , SVG,
IE 5.5.
Microsoft ( ) VML
W3 ,
. VML, Mi
crosoft, W3C http://www.w3.org/TR/NOTE'
VML. : ,
W3C, VML ,
Microsoft.
VML ,
. 1
. Microsoft
, W3C,
. , . . ,
, . VML ,
, ,
IE .
, VML
, ,
, .
VML XML, HTML, IE
XHTML, DOM
, , document.crea
teElementNS(). VML IE
HTML ( ,
IE). HTML, VML,
, :
<html xmlns:v="urn:schemasmicrosoftcom:vml">
,
IE () :
1
570
22.
CSS
, :
<style>v\:* { behavior: url(#default#VML); }</style>
,
VML HTML, ,
SVG, . 22.4:
<html xmlns:v="urn:schemasmicrosoftcom:vml">
<head><style>v\:* { behavior: url(#default#VML); }</style></head>
<body>
:<v:rect style="width:10px;height:10px;" fillcolor="red"/>
:<v:oval style="width:10px;height:10px;" fillcolor="blue"/>
</body>
</html>
,
JavaScript
. 22.10 ,
VML.
SVG, SVG
VML.
makeVMLCanvas(), pieChart() ,
.
, ,
SVG . 22.5.
22.10. JavaScript VML
<!
HTML, VML,
>
<html xmlns:v="urn:schemasmicrosoftcom:vml">
<head>
<!
VML VML
>
<style>v\:* { behavior: url(#default#VML); }</style>
<script>
/*
* VML <v:group>, .
* : .
*/
function makeVMLCanvas(id, pixelWidth, pixelHeight) {
var vml = document.createElement("v:group");
vml.setAttribute("id", id);
vml.style.width = pixelWidth + "px";
vml.style.height = pixelHeight + "px";
vml.setAttribute("coordsize", pixelWidth + " " + pixelHeight);
// .
var rect = document.createElement("v:rect");
22.4. VML
571
572
22.
icon.style.left = lx + "px"; // CSS
icon.style.top = (ly+i*30) + "px";
icon.style.width = "20px"; // CSS
icon.style.height = "20px";
icon.setAttribute("fillcolor", colors[i]); //
icon.setAttribute("stroke", "black");
//
icon.setAttribute("strokeweight", "2");
//
canvas.appendChild(icon);
// ""
// VML ,
// HTML,
// VML
var label = document.createElement("div"); // <div>
label.appendChild(document.createTextNode(labels[i])); //
label.style.position = "absolute"; // CSS
label.style.left = (lx + 30) + "px";
label.style.top = (ly + 30*i + 5) + "px";
label.style.fontFamily = "sansserif"; //
label.style.fontSize = "16px";
canvas.appendChild(label); //
}
}
function init() {
var canvas = makeVMLCanvas("canvas", 600, 400);
document.body.appendChild(canvas);
pieChart(canvas, [12, 23, 34, 45], 200, 200, 150,
["red", "blue", "yellow", "green"],
["", "", "", ""],
400, 100);
}
</script>
</head>
<body onload="init()">
</body>
</html>
22.5. <canvas>
<canvas>. HTML
.
, JavaScript
<canvas>. <can
vas> Apple Safari 1.3. (
HTML , HTML
Safari Dashboard (
) Mac OS X, Apple
Dashboard.)
Firefox 1.5 Opera 9 Safari
<canvas>. <canvas> IE
JavaScript (
573
22.5. <canvas>
5 (5,5)
}
</script>
</head>
<body>
: <canvas id="square" width=10 height=10></canvas>.
1
"2d"
,
. <canvas>
, , ,
"3d".
574
22.
, SVG VML
, ,
. Canvas
,
, ,
beginPath() arc() .
, , fill(),
.
, fillStyle.
,
Canvas, , .
<canvas>,
HTML <canvas>,
CSS.
22.11 ,
<canvas>.
SVG VML.
Canvas, .
22.11. <canvas>
<html>
<head>
<script>
// <canvas> id .
// : <canvas>
function makeCanvas(id, width, height) {
var canvas = document.createElement("canvas");
canvas.id = id;
canvas.width = width;
canvas.height = height;
return canvas;
}
/**
* <canvas>,
* , id.
* data :
* .
* cx cy, r.
* HTML colors[].
* (lx,ly), labels[].
*/
function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
// canvas id
if (typeof canvas == "string") canvas = document.getElementById(canvas);
//
var g = canvas.getContext("2d");
22.5. <canvas>
575
// 2
g.lineWidth = 2;
g.strokeStyle = "black";
//
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
// ( )
var angles = []
for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
//
startangle = Math.PI/2; // ,
//
for(var i = 0; i < data.length; i++) {
//
var endangle = startangle + angles[i];
//
g.beginPath();
//
g.moveTo(cx,cy);
//
// startangle endangle
g.arc(cx,cy,r,startangle, endangle, false);
g.closePath();
//
g.fillStyle = colors[i]; //
g.fill();
//
g.stroke();
// ()
// , .
startangle = endangle;
//
g.fillRect(lx, ly+30*i, 20, 20);
g.strokeRect(lx, ly+30*i, 20, 20);
// . Canvas
// ,
// HTML.
// canvas, CSS.
// , <canvas>
var label = document.createElement("div");
label.style.position = "absolute";
label.style.left = (canvas.offsetLeft + lx+30)+"px";
label.style.top = (canvas.offsetTop+ly+30*i4) + "px";
label.style.fontFamily = "sansserif";
label.style.fontSize = "16px";
label.appendChild(document.createTextNode(labels[i]));
document.body.appendChild(label);
}
}
function init() {
// canvas
var canvas = makeCanvas("canvas", 600, 400);
//
document.body.appendChild(canvas);
576
22.
//
pieChart("canvas", [12, 23, 34, 45], 200, 200, 150,
["red", "blue", "yellow", "green"],
["", "", "", ""],
400, 100);
}
</script>
</head>
<body onload="init()"></body>
</html>
22.6. Flash
: <canvas>
Safari 1.3, Firefox 1.5 Opera 9; VML (
) IE, SVG
Firefox 1.5. , SVG
, .
, (
) , Flash Adobe ( Macrome
dia). Flash , Acti
onScript ( JavaScript). 6 Flash
,
ActionScript. , Flash 6 7
JavaScript Action
Script, JavaScript
Flash ,
ActionScript.
Flash 8,
. Flash 8 Exter
nalInterface, ActionScript,
JavaScript.
23 , Flash 6 7.
Flash .swf,
, JavaScript
.1 Ac
tionScript, 22.12.
22.12. Canvas.as
import flash.external.ExternalInterface;
class Canvas {
// mtasc
// main() SWF.
1
22.13, ,
, .
Adobe.
22.6. Flash
577
Canvas.as, 22.12,
Canvas.swf,
Flash. , ,
,
Flash IDE Adobe Acti
onScript.1
, Flash
. , curveTo() ,
(, ). ,
1
mtasc (http://www.
mtasc.org) mtasc swf Canvas.swf main version 8
header 500:500:1 Canvas.as.
578 , .
578
22.
.
Flash SWF:
, ,
, Flash
.
, Flash,
ActionScript JavaScript ( 22.13 JavaScript).
22.13 ,
Canvas.swf HTML.
, insertCanvas() .
wedge(), Flash
. pieChart(),
wedge() .
onload, Flash
.
22.13. JavaScript Flash
<html>
<head>
<script>
// Flash
// .
// <embed> Netscape <object>
// FlashObject, (Geoff Stearns).
// http://blog.deconcept.com/flashobject/
function insertCanvas(containerid, canvasid, width, height) {
var container = document.getElementById(containerid);
if (navigator.plugins && navigator.mimeTypes&&navigator.mimeTypes.length){
container.innerHTML =
"<embed src='Canvas.swf' type='application/xshockwaveflash' " +
"width='" + width +
"' height='" + height +
"' bgcolor='#ffffff' " +
"id='" + canvasid +
"' name='" + canvasid +
"'>";
}
else {
container.innerHTML =
"<object classid='clsid:D27CDB6EAE6D11cf96B8444553540000' "+
"width='" + width +
"' height='" + height +
"' id='"+ canvasid + "'>" +
" <param name='movie' value='Canvas.swf'>" +
" <param name='bgcolor' value='#ffffff'>" +
"</object>";
}
}
// Flash , ,
// .
22.6. Flash
// , .
// : .
function wedge(canvas, cx, cy, r, startangle, endangle, color) {
//
var x1 = cx + r*Math.sin(startangle);
var y1 = cy r*Math.cos(startangle);
canvas.beginFill(color, 100); //
canvas.moveTo(cx, cy);
//
canvas.lineTo(x1, y1);
//
// 45
// arc() method
while(startangle < endangle) {
var theta;
if (endanglestartangle > Math.PI/4) theta = startangle+Math.PI/4;
else theta = endangle;
arc(canvas,cx,cy,r,startangle,theta);
startangle += Math.PI/4;
}
canvas.lineTo(cx, cy); //
canvas.endFill();
//
// .
// endangle startangle 45 .
// startangle.
// ,
// , .
function arc(canvas, cx, cy, r, startangle, endangle) {
//
var x2 = cx + r*Math.sin(endangle);
var y2 = cy r*Math.cos(endangle);
var theta = (endangle startangle)/2;
//
var l = r/Math.cos(theta);
// :
var alpha = (startangle + endangle)/2;
//
var controlX = cx + l * Math.sin(alpha);
var controlY = cy l * Math.cos(alpha);
// Flash API, .
canvas.curveTo(controlX, controlY, x2, y2);
}
}
/**
* Flash,
* id.
* data : .
* (cx, cy),
* r.
* colors Flash colors[].
* , (lx,ly),
579
580
22.
* labels[].
*/
function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
// id
if (typeof canvas == "string")
canvas = document.getElementById(canvas);
// , , 2 .
canvas.lineStyle(2, 0x000000, 100);
//
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
// ( ) .
var angles = []
for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*Math.PI*2;
//
startangle = 0;
for(var i = 0; i < data.length; i++) {
// ,
var endangle = startangle + angles[i];
// :
wedge(canvas, cx, cy, r, startangle, endangle, colors[i]);
// , .
startangle = endangle;
//
canvas.beginFill(colors[i], 100);
canvas.moveTo(lx, ly+30*i);
canvas.lineTo(lx+20, ly+30*i);
canvas.lineTo(lx+20, ly+30*i+20);
canvas.lineTo(lx, ly+30*i+20);
canvas.lineTo(lx, ly+30*i);
canvas.endFill();
//
canvas.addText(labels[i], lx+30, ly+i*30, 100, 20, //
i, //
"Helvetica", 16);
//
}
}
// , Flash .
// : Flash ,
window.onload = function() {
insertCanvas("placeholder", "canvas", 600, 400);
pieChart("canvas", [12, 23, 34, 45], 200, 200, 150,
[0xff0000, 0x0000ff, 0xffff00, 0x00ff00],
["", "", "", ""],
400, 100);
}
</script>
</head>
22.7. Java
581
<body>
<div id="placeholder"></div>
</body>
</html>
22.7. Java
Java Sun Microsystems
, Flash,
,
. Java2D API
, Java 1.2.
, Flash API,
(, ),
<canvas>. Java2D SVG.
Java2D JavaScript.
22.7.1. Java
Java ,
Flash: Canvas,
Java2D.
JavaScript.
( Java JavaScript
23.) , 22.14.
:
Java2D. Flash
, .
Java2D .
,
, .
22.14
,
. 22.5.
22.14. Java' Canvas.java,
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.geom.*;
java.awt.image.*;
/**
* : API
* JavaScript .
*/
public class Canvas extends Applet {
BufferedImage image; //
Graphics2D g;
//
582
22.
//
public void init() {
//
// .
int w = getWidth();
int h = getHeight();
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//
g = image.createGraphics();
//
g.setPaint(Color.WHITE);
g.fillRect(0, 0, w, h);
//
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
// ,
// .
// . JavaScript,
// , repaint().
public void paint(Graphics g) { g.drawImage(image, 0, 0, this); }
//
// , Java2D API
public void setLineWidth(float w) { g.setStroke(new BasicStroke(w)); }
public void setColor(int color) { g.setPaint(new Color(color)); }
public void setFont(String fontfamily, int pointsize) {
g.setFont(new Font(fontfamily, Font.PLAIN, pointsize));
}
//
public void fillRect(int x, int y, int w, int h) { g.fillRect(x,y,w,h); }
public void drawRect(int x, int y, int w, int h) { g.drawRect(x,y,w,h); }
public void drawString(String s, int x, int y) { g.drawString(s, x, y); }
//
public void fill(Shape shape) { g.fill(shape); }
public void draw(Shape shape) { g.draw(shape); }
//
// . Java2D API .
public Shape createRectangle(double x, double y, double w, double h) {
return new Rectangle2D.Double(x, y, w, h);
}
public Shape createEllipse(double x, double y, double w, double h) {
return new Ellipse2D.Double(x, y, w, h);
}
public Shape createWedge(double x, double y, double w, double h,
double start, double extent) {
return new Arc2D.Double(x, y, w, h, start, extent, Arc2D.PIE);
}
22.7. Java
583
javac,
Canvas.class:
% javac Canvas.java
Canvas.class HTML
, , :
<head>
<script>
window.onload = function() {
var canvas = document.getElementById('square');
canvas.setColor(0x0000ff); // :
canvas.fillRect(0,0,10,10);
canvas.repaint();
canvas = document.getElementById('circle');
canvas.setColor(0xff0000);
canvas.fill(canvas.createEllipse(0,0,10,10));
canvas.repaint();
};
</script>
</head>
<body>
:
<applet id="square" code="Canvas.class" width=10 height=10></applet>
:
<applet id="circle" code="Canvas.class" width=10 height=10></applet>
</body>
onload
, .
Java 5 onload
,
.
, onload, , ,
.
22.15 JavaScript,
Java Canvas. makeCan
vas(), . ,
onload, ,
, , .
22.15. JavaScript Java
<head>
<script>
// Java Canvas
function pieChart(canvas, data, cx, cy, r, colors, labels, lx, ly) {
// ,
if (typeof canvas == "string") canvas = document.getElementById(canvas);
// 2 .
// sansserif, , 16 .
canvas.setLineWidth(2);
584
22.
canvas.setFont("SansSerif", 16);
//
var total = 0;
for(var i = 0; i < data.length; i++) total += data[i];
//
var angles = []
for(var i = 0; i < data.length; i++) angles[i] = data[i]/total*360;
startangle = 90; //
//
for(var i = 0; i < data.length; i++) {
//
var arc = canvas.createWedge(cxr, cyr, r*2, r*2,
startangle, angles[i]);
canvas.setColor(colors[i]);
//
canvas.fill(arc);
//
canvas.setColor(0x000000);
//
canvas.draw(arc);
//
startangle = angles[i];
//
//
canvas.setColor(colors[i]);
//
canvas.fillRect(lx, ly+30*i, 20, 20); //
canvas.setColor(0x000000);
//
canvas.drawRect(lx, ly+30*i, 20, 20); //
//
//
canvas.drawString(labels[i], lx+30, ly+30*i+18);
}
//
canvas.repaint(); //
}
// !
function draw() {
pieChart("canvas", [12, 23, 34, 45], 200, 200, 150,
[0xff0000, 0x0000ff, 0xffff00, 0x00ff00], //
["", "", "", ""],
400, 100);
}
</script>
</head>
<body>
<applet id="canvas" code="Canvas.class" width=600 height=400></applet>
<button onclick="draw()">!</button>
</body>
22.7.2.
Java
Java2D API
, ,
22.7. Java
585
PNG URL
data:.
.
,
Java, LiveConnect (.
12), Firefox .
(sparklines), ,
. :
sparkline (Edward Tufte),
:
,
, , . ,
,
. (
Beautiful Evidence [Graphics Press].)
22.16 ,
. JavaScript make
Sparkline() LiveConnect (
) Java2D.
22.16.
JavaScript Java
<head>
<script>
/**
* data ,
*
* dx
* config ,
* :
* height:
* ymin, ymax: Y
* backgroundColor: .
* lineWidth:
* lineColor: HTML #
* dotColor: ,
* bandColor: , bandMin bandMax
*
,
*
""
*
,
*/
function makeSparkline(data, dx, config) {
var width = data.length * dx + 1; //
var yscale = config.height/(config.ymax config.ymin); //
//
function x(i) { return i * dx; }
// Y
//
586
22.
function y(y) { return config.height (y config.ymin)*yscale; }
// HTML java.awt.Color
function color(c) {
c = c.substring(1);
// #
if (c.length == (3)) { // 6
//
c = c.charAt(0) + c.charAt(0) + c.charAt(1) + c.charAt(1) +
c.charAt(2) + c.charAt(2);
}
var red = parseInt(c.substring(0,2), 16);
var green = parseInt(c.substring(2,4), 16);
var blue = parseInt(c.substring(4,6), 16);
return new java.awt.Color(red/255, green/255, blue/255);
}
//
var image = new java.awt.image.BufferedImage(width, config.height,
java.awt.image.BufferedImage.TYPE_INT_RGB);
// Graphics,
var g = image.createGraphics( );
// . ,
g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
//
g.setPaint(color(config.backgroundColor));
g.fillRect(0, 0, width, config.height);
// bandColor ,
if (config.bandColor) {
g.setPaint(color(config.bandColor));
g.fillRect(0, y(config.bandMax),
width, y(config.bandMin)y(config.bandMax));
}
//
var line = new java.awt.geom.GeneralPath( );
line.moveTo(x(0), y(data[0]));
for(var i = 1; i < data.length; i++) line.lineTo(x(i), y(data[i]));
// ,
g.setPaint(color(config.lineColor));
//
g.setStroke(new java.awt.BasicStroke(config.lineWidth)); //
g.draw(line);
// !
// dotColor ,
if (config.dotColor) {
g.setPaint(color(config.dotColor));
var dot=new java.awt.geom.Ellipse2D$Double(x(data.length1).75,
y(data[data.length1]).75,
1.5, 1.5)
g.draw(dot);
}
// PNG
22.7. Java
587
Java
Flash
, (plug'in),
,
. (, ,
) Java Sun Microsys
tems Flash Adobe ( Macromedia).
Java , '
, Java. Java
, , ,
,
. ,
, Java
, .
, ,
XML , ,
.
Java 6 .
Flash
. ,
, ,
. Flash Action
Script. ActionScript JavaScript,
,
, () .
ActionScript Flash
( , Java) ,
, XML
.
589
Java Flash
.
,
DHTML. ,
,
JavaScript.
, . JavaScript
Java, Flash. : Java
Flash JavaScript.
, . ,
JavaScript, Java ActionScript ,
Java Flash
, ,
.
, JavaScript
Java. ( 22.14, Java
.)
, Firefox
JavaScript Java
. ( 22.16.)
JavaScript Java
, JavaScript
JavaScript, ,
Java DOM API ,
.
Java JavaScript 12,
. 12 ,
JavaScript Java
, Java.
12 JavaScript .
LiveConnect,
JavaScript Java,
. ,
, 12, Rhino LiveConnect
JavaScript .
Java , ,
, Java.
, .
Java,
Flash , JavaScript
ActionScript, Flash, Ac
tionScript, , JavaScript.
, Flash,
Flash 8 .
590
Flash
. 22 Flash Action
Script
(. 22.12), 19
Flash (. 19.4).
23.1.
HTML
, . 15 , Java
, , Document.app
lets[]. name id,
Document. , ,
<applet name="chart">, : document.chart.
id,
Document.getElementById().
,
JavaScript,
HTML <applet>.
Canvas, 22.14.
HTML "canvas" id,
:
var canvas = document.getElementById('canvas');
canvas.setColor(0x0000ff);
canvas.fillRect(0,0,10,10);
canvas.repaint( );
JavaScript ,
. , name="chart"
, (Java):
public int numPoints;
public double[] points;
JavaScript :
for(var i = 0; i < document.chart.numPoints; i++)
document.chart.points[i] = i*i;
,
Java JavaScript, . Java
.
JavaScript .
(integer) Java JavaScript,
JavaScript Java double.
,
. JavaScript
Java 12,
.
, JavaObject, JavaArray, JavaClass JavaPackage.
: 12 LiveConnect,
23.1.
591
Netscape, . ,
IE JavaScript Java
ActiveX.
Java JavaScript
.
, , Java Java
, JavaScript
, , .
Canvas 22.14. ,
Shape. JavaScript
Shape ,
Shape.
23.1 Java, ,
JavaScript .
getText() URL ( ,
) Java.
, HTML :
<! HTML >
<body onload="alert(document.http.getText('GetText.html'));">
<applet name="http" code="GetTextApplet.class" width="1" height="1"></applet>
</body>
23.1 Java,
, ,
.
, ,
JavaScript.
23.1. ,
import java.applet.Applet;
import java.net.URL;
import java.io.*;
public class GetTextApplet extends Applet {
public String getText(String url)
throws java.net.MalformedURLException, java.io.IOException
{
URL resource = new URL(this.getDocumentBase(), url);
InputStream is = resource.openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuilder text = new StringBuilder();
String line;
while((line = in.readLine()) != null) {
text.append(line);
text.append("\n");
}
in.close();
return text.toString();
}
}
592
23.2. Java
Firefox
, Java,
. LiveConnect JavaScript
, ,
Java .
, , Internet Explorer, .
,
Java, Packages Java,
. Packages.java.lang
java.lang, Packages.java.lang.System java.lang.System.
java
Packages.java ( . ,
Packages). , JavaScript
java.lang.System :
// System.getProperty()
var javaVersion = java.lang.System.getProperty("java.version");
: LiveConnect Java
new JavaScript. 23.2
JavaScript, Java
. : JavaScript
Java. 12,
<script> HTML. . 23.1
, Java Firefox.
23.2. Java'
<script>
//
// javax.*
var javax = Packages.javax;
// Java
var frame = new javax.swing.JFrame("Hello World");
593
Java,
, ,
, . JavaScript,
, java.io.File,
, .
23.3. JavaScript
Java
, Java JavaScript,
: JavaScript Java.
Java JavaScript
netscape.javascript.JSObject. ( JSObject
IV .)
JavaScript. ,
JavaScript,
. :
public final class JSObject extends Object {
// JSObject
// .
public static JSObject getWindow(java.applet.Applet applet);
//
public Object getMember(String name); //
public Object getSlot(int index);
//
public void setMember(String name, Object value); //
public void setSlot(int index, Object value);
//
public void removeMember(String name);
//
public Object call(String name, Object args[]); //
public Object eval(String s);
//
public String toString();
//
protected void finalize();
}
594
JSObject, Window,
JSObject, JavaScript:
import netscape.javascript.JSObject; //
...
// JSObject, Window
JSObject win = JSObject.getWindow(this); // window
// getMember() JSObject,
// Document
JSObject doc = (JSObject)win.getMember("document"); // .document
// call() JSObject,
//
JSObject div = (JSObject)doc.call("getElementById", // .getElementById('test')
new Object[] { "test" });
. , getMember()
call() Object, , ,
, JSObject.
, call() JavaScript,
Java Object.
, .
JSObject eval(). Java
, JavaScript: ,
JavaScript. eval() ,
JSObject. , CSS
eval():
JSObject win = JSObject.getWindow(this);
win.eval("document.getElementById('test').style.backgroundColor = 'gray';");
eval(),
:
JSObject win = JSObject.getWindow(this);
JSObject doc = (JSObject)win.getMember("document");
JSObject div = (JSObject)doc.call("getElementById",
new Object[] { "test" });
JSObject style = (JSObject)div.getMember("style");
style.setMember("backgroundColor", "gray");
// window
// .document
// .getElementById('test')
// .style
// .backgroundColor="gray"
23.3.1. ,
JSObject
, ,
HTML. JSObject,
.
, JavaScript,
, netscape.javascript.JSOb
ject. ,
Java, . ,
Java Sun Microsystems,
595
. JSObject jre/lib/plugin.jar
Java. , ,
JSObject, ,
, Java:
% javac
cp /usr/local/java/jre/lib/plugin.jar ScriptedApplet.java
, JavaScript,
,
JavaScript,
(, , )
. ,
<applet> ( <object>, <embed>) mayscript.
:
<applet code="ScriptingApplet.class" mayscript width="300" height="300">
</applet>
mayscript
JSObject.
23.3.2.
Java JavaScript
JSObject
Java JavaScript,
. , JSObject,
12 ,
LiveConnect. , ,
JSObject, ,
Java JavaScript.
Java JavaScript,
:
JavaScript java.lang.Double.
JavaScript java.lang.String.
JavaScript java.lang.Boolean.
JavaScript null Java null.
JavaScript undefined :
Java 5 Internet Explorer undefined
null, Firefox "undefined".
Java JavaScript
JavaScript,
, , ,
. Firefox 1.0 Java 5 Java
, JavaScript JavaObject (
LiveConnect).
IE 6 Java 5
:
596
Java JavaScript.
Firefox IE
JavaScript ,
. , ,
,
Number(), String() Boolean(),
.
,
JSObject.eval() ,
JavaScript.
597
23.4. Flash*
java.applet.Applet;
com.sun.java.browser.dom.*;
org.w3c.dom.*;
org.w3c.dom.css.*;
//
//
//
//
Applet
Common DOM API
W3C core DOM API
W3C CSS DOM API
// .
// JavaScript. Common DOM
// , .
public class DOMApplet extends Applet {
// .
public void setBackgroundColor(final String id, final String color)
throws DOMUnsupportedException, DOMAccessException
{
// DOMService
DOMService service = DOMService.getService(this);
// invokeAndWait() DOMService
// DOMAction
service.invokeAndWait(new DOMAction() {
// DOM run()
public Object run(DOMAccessor accessor) {
// Document DOMAccessor
// :
Document d = accessor.getDocument(DOMApplet.this);
//
Element e = d.getElementById(id);
// ElementCSSInlineStyle,
// getStyle().
// CSS2Properties.
CSS2Properties style =
(CSS2Properties) ((ElementCSSInlineStyle)e).getStyle( );
// ,
style.setBackgroundColor(color);
// DOMAction ,
return null;
}
});
}
}
23.4. Flash
, JavaScript Java
, Flash
Flash.
Flash. , JavaScript
Flash: ,
. . ActionScript
, Flash.
, Flash 8.
598
, , ActionScript
JavaScript. 23.4.5
, (JavaScript
ActionScript)
JavaScript ActionScript. 23.5 ,
Flash 8.
Flash , ActionScript,
Flash Flash
Adobe. Flash
ActionScript,
SWF (. . Flash)
ActionScript mtasc (http://www.
mtasc.org).
.
ActionScript ,
Flash. ,
, Acti
onScript, http://www.adobe.com/ support/flash/acti'
on_scripts/actionscript_dictionary/.
23.4.1. Flash
Flash,
HTML, JavaScript .
,
: IE , <object>
, <object>
<embed>. <object> HTML,
Flash JavaScript ,
<embed>.
IE HTML
, <object> ,
IE, <embed> IE. Flash
mymovie.swf movie:
<![if IE]>
<object id="movie" type="application/xshockwaveflash"
width="300" height="300">
<param name="movie" value="mymovie.swf">
</object>
<![endif]><![if !IE]> <>
<embed name="movie" type="application/xshockwaveflash"
src="mymovie.swf" width="300" height="300">
</embed>
<!> <![endif]>
599
23.4. Flash*
23.4.2. Flash
Flash HTML JavaScript
HTML, ,
Flash, .
, :
var flash = window.movie
if (flash.IsPlaying()) {
flash.StopPlay();
flash.Rewind();
}
if (flash.PercentLoaded(
flash.Play();
flash.Zoom(50);
flash.Pan(25, 25, 1);
flash.Pan(100, 0, 0);
||
//
//
//
document.movie; //
,
) == 100) //
//
//
//
//
,
.
50 %
25 %
100
Flash IV
, 23.5.
23.4.3. Flash
, Flash, ActionScript
, . Java
: <applet>.
Flash 8 .
,
Flash,
.
Flash SetVariable(),
GetVariable().
ActionScript. InvokeFunction() ,
ActionScript JavaScript
SetVariable(). ActionScript
watch(),
:
, . Acti
onScript:
600
/* ActionScript */
//
//
// _root . SetVariable()
// GetVariable() .
_root.arg1 = 0;
_root.arg2 = 0;
_root.result = 0;
//
_root.multiply = 0;
// Object.watch()
// "multiply". :
//
_root.watch("multiply", function() {
_root.result = Number(_root.arg1) * Number(_root.arg2);
// , .
return 0;
});
, Flash
, JavaScript. , Ac
tionScript, , :
/* JavaScript */
// Flash
function multiply(x, y) {
var flash = window.movie || document.movie;
flash.SetVariable("arg1", x);
flash.SetVariable("arg2", y);
flash.SetVariable("multiply", 1);
var result = flash.GetVariable("result");
return Number(result);
}
//
//
//
//
//
//
Flash
23.4. Flash*
601
, Internet Explorer .
, Flash IE,
JavaScript
Microsoft VBScript. VBScript, ,
JavaScript. ,
fscommand() IE, HTML
( , movie).
<script language="VBScript">
sub movie_FSCommand(byval command, byval args)
call movie_DoFSCommand(command, args) ' JavaScript
end sub
</script>
, ,
HTML. , VBScript,
<script> .
602
class Box {
static function main() {
// ActionScript JavaScript.
// .
var drawBox = function(x,y,w,h) {
_root.beginFill(0xaaaaaa, 100);
_root.lineStyle(5, 0x000000, 100);
_root.moveTo(x,y);
_root.lineTo(x+w, y);
_root.lineTo(x+w, y+h);
_root.lineTo(x, y+h);
_root.lineTo(x,y);
_root.endFill();
return w*h;
}
//
// JavaScript Flash 8. ,
// ,
// .
_root.arg1 = 0;
_root.arg2 = 0;
_root.arg3 = 0;
_root.arg4 = 0;
_root.result = 0;
// ,
// .
_root.drawBox = 0;
// Object.watch()
// " "
// . ,
// . , JavaScript
// SetVariable.
_root.watch("drawBox", //
function() { // ,
// drawBox(),
// .
_root.result = drawBox(Number(_root.arg1),
Number(_root.arg2),
Number(_root.arg3),
Number(_root.arg4));
// 0,
// .
return 0;
});
// ActionScript .
// fscommand(),
// .
_root.onMouseDown = function() {
fscommand("mousedown", _root._xmouse + "," + _root._ymouse);
}
23.4. Flash*
// fscommand()
// JavaScript, Flash .
fscommand("loaded", "");
}
}
23.5. Flash'
<!
Flash, .
, IE <object id="">,
<embed name="">.
,
IE.
>
<![if IE]>
<object id="movie" type="application/xshockwaveflash"
width="300" height="300">
<param name="movie" value="Box1.swf">
</object>
<![endif]><![if !IE]> <>
<embed name="movie" type="application/xshockwaveflash"
src="Box1.swf" width="300" height="300">
</embed>
<!> <![endif]>
<!
HTML ,
.
: Draw . Flash
, JavaScript,
JavaScript .
>
<form name="f" onsubmit="return false;">
<button name="button" onclick="draw()" disabled>Draw</button>
<button onclick="zoom()">Zoom</button>
<button onclick="pan()">Pan</button>
</form>
<script>
// Flash
// .
function draw() {
// Flash.
// id name <object> <embed>
// "movie", "movie".
// IE window,
// document.
var flash = window.movie || document.movie; // Flash.
//
//
//
//
if
, ,
. , ,
, , Flash ,
(flash.PercentLoaded() != 100) return;
603
604
}
function zoom() {
var flash = window.movie || document.movie; // Flash.
flash.Zoom(50);
}
function pan() {
var flash = window.movie || document.movie; // Flash.
flash.Pan(50, 50, 1);
}
// , Flash fscommand().
// Flash.
// ,
// . "movie",
// id/name <object> <embed>,
// .
function movie_DoFSCommand(command, args) {
if (command=="loaded") {
// Flash , ,
// .
document.f.button.disabled = false;
}
else if (command == "mousedown") {
// Flash , .
// Flash .
// , , Flash.
var coords = args.split(",");
alert("Mousedown: (" + coords[0] + ", " + coords[1] + ")");
}
// .
else if (command == "debug") alert("Flash debug: " + args);
else if (command == "eval") eval(args);
}
</script>
<script language="VBScript">
' JavaScript, Visual Basic
' Scripting Edition Microsoft. ,
' Internet Explorer fscommand() Flash.
' , VBScript.
' , .
sub movie_FSCommand(byval command, byval args)
23.5. Flash 8
605
23.5. Flash 8
Flash 8 ExternalInterface,
JavaScript Flash.
ExternalInterface call(),
JavaScript
. addCallback(),
ActionScript JavaScript
. ExternalInterface
.
Exter
nalInterface, 23.4 23.5. 23.6
ActionScript, 23.7 Java
Script ( <object>, <embed> <form>
23.5 ).
,
ExternalInterface. , ExternalInterface.add
Callback() 22.12.
23.6. ActionScript', ExternalInterface
/**
* Box2.as: ActionScript
* JavaScript Flash ExternalInterface Flash 8.
*
* :
*
* mtasc version 8 header 300:300:1 main swf Box2.swf Box2.as
*
* Flash IDE, Box.main().
*/
import flash.external.ExternalInterface;
class Box {
static function main() {
// ActionScript ExternalInterface.
// JavaScript,
// Flash 8 .
// addCallback ,
// JavaScript.
// ActionScript, ,
// 'this'.
// .
ExternalInterface.addCallback("drawBox", null, function(x,y,w,h) {
_root.beginFill(0xaaaaaa, 100);
_root.lineStyle(5, 0x000000, 100);
_root.moveTo(x,y);
_root.lineTo(x+w, y);
606
23.7. Flash
ExternalInterface
<script>
// ActionScript ExternalInterface.addCallback,
// Flash.
function draw() {
var flash = window.movie || document.movie; // Flash
return flash.drawBox(100, 100, 100, 50);
//
}
// Flash ExternalInterface.call().
function flashReady() { document.f.button.disabled = false; }
function reportMouseClick(x, y) { alert("click: " + x + ", " + y); }
</script>
JavaScript
,
,
JavaScript. ,
, .
:
Arguments
Array
Boolean
Date
Error
Global
JavaArray
JavaClass
JavaObject
JavaPackage
Function
Math
Number
Object
RegExp
String
JavaScript
, ,
, JavaScript.
,
.
!
. ,
, ,
. , replace()
String, String.replace(), replace.
JavaScript ,
eval() NaN. .
,
.
JavaScript Global (
).
,
. , ,
. ,
, ,
. ,
.
JavaScript
,
. .
,
, , .
.
,
.
, , ,
, ,
. ,
610
JavaScript
, .
9 , JavaScript
. , String Object,
HTMLDocument Document,
Node. String
: ObjectString, HTMLDocument: NodeDocument
HTMLDocument. , ,
.
, ,
. Array.to
String().
,
. ,
.
, ,
, .
. ,
JavaScript ( Window),
DOM, . , Ar
ray.concat():
.concat(, ...)
, .
, , Java
Script, .
, .
(...) ,
611
. concat,
, JavaScript ,
.
, ,
W3C
.
. , Document.getEle
mentById() :
Element getElementById(String elementId);
Java, , getEle
mentById() Element
elementId. Document
, document .
,
,
, , .
, :
1
. , ,
1.
2
2.
, ,
.
, ,
,
.
,
. , Node
, nodeType.
, .
: ,
.
,
, , .
III
. IV .
IV ,
. IV DOM
612
JavaScript
. ,
III, .
:
prop1
prop1.
, ,
,
.
readonly integer prop2
prop2. ,
, .
.
, , .
, ,
, .
. .
.
,
, , , .
. , ,
, ,
, , .
, , , ,
,
(, ).
.
.
, .
,
. , , .
.
,
. ,
JavaScript.
.
, .
.
613
arguments[]
arguments[]
ECMAScript v1
arguments
arguments[] ,
Arguments .
, .
arguments , , ,
. Argu
ments .
Arguments; 8
Arguments
ECMAScript v1
ObjectArguments
arguments
arguments[n]
Arguments .
, ,
, length, .
, . 0
, 1 . . ,
, Arguments ,
.
callee
.
length
, ,
Arguments.
, Arguments,
arguments Arguments.
Arguments ,
, .
length, callee
.
614
Arguments.callee
Arguments
callee. Array,
Arguments.length , Array.length,
.
Arguments .
, Arguments
, . Arguments
.
, Arguments,
Arguments , .
Function; 8
Arguments.callee
ECMAScript v1
arguments.callee
arguments.callee , .
.
.
// callee
// ,
var factorial = function(x) {
if (x < 2) return 1;
else return x * arguments.callee(x1);
}
var y = factorial(5); // 120
Arguments.length
ECMAScript v1
arguments.length
length Arguments ,
. .
:
, .
Function.length. , ,
, Array.length.
615
Array
// Arguments, ,
function check(args) {
var actual = args.length;
//
var expected = args.callee.length; //
if (actual != expected) {
// ,
throw new Error(" : : " +
expected + "; " + actual);
}
}
// , ,
function f(x, y, z) {
check(arguments); //
return x + y + z; //
}
Array.length, Function.length
Array
ECMAScript v1
ObjectArray
new Array()
new Array()
new Array(0, 1, ..., n)
. (length)
.
0, ... n
.
Array() ,
, length
.
. Array()
, length 0.
.
,
. Array() ( new),
, new.
RangeError
Array() ,
RangeError, 2321.
616
Array
ECMAScript v3 .
, ,
, .
. :
var a = [1, true, 'abc'];
var b = [a[0], a[0]*2, f(x)];
length
, , ,
, , ,
.
.
concat()
.
join()
.
pop()
.
push()
.
reverse()
.
shift()
.
slice()
.
sort()
.
splice()
, .
toLocaleString()
.
toString()
.
unshift()
.
JavaScript, 7.
617
Array.concat()
Array.concat()
ECMAScript v3
.concat(, ...)
, ...
, .
,
.
concat() ,
. .
concat() ,
, .
var a = [1,2,3];
a.concat(4, 5)
a.concat([4,5]);
a.concat([4,5],[6,7])
a.concat(4, [5,[6,7]])
//
//
//
//
[1,2,3,4,5]
[1,2,3,4,5]
[1,2,3,4,5,6,7]
[1,2,3,4,5,[6,7]]
Array.join()
ECMAScript v1
.join()
.join()
,
. , .
,
.
join()
, .
.
618
Array.length
( )
split() String. . ,
String.split().
String.split()
Array.length
ECMAScript v1
.length
length ,
. ,
0,
length .
length
Array(). length,
:
a = new Array();
// a.length
b = new Array(10);
// b.length
c = new Array("one", "two", "three"); // c.length
c[3] = "four";
// c.length
c[10] = "blastoff";
// c.length
0
10
3
4
11
, length.
length , ,
. length ( ),
, , ,
undefined.
Array.pop()
ECMAScript v3
.pop()
.
pop() ,
. , pop()
undefined.
619
Array.push()
pop() push() ,
, . :
var stack = [];
stack.push(1, 2);
stack.pop();
stack.push([4,5]);
stack.pop()
stack.pop();
//
//
//
//
//
//
stack:
stack:
stack:
stack:
stack:
stack:
[]
[1,2] 2
[1] 2
[1,[4,5]] 2
[1] [4,5]
[] 1
Array.push()
Array.push()
ECMAScript v3
.push(, ...)
, ...
, .
.
push() .
, . push() pop()
, ,
. Array.pop().
Array.pop()
Array.reverse()
ECMAScript v1
.reverse()
reverse() Array
. , . .
, . ,
.
620
Array.shift()
Array.shift()
ECMAScript v3
.shift()
.
shift() ,
. , shift() undefined.
: shift() ,
.
shift() Array.pop() ,
, . shift()
unshift().
Array.pop(), Array.unshift()
Array.slice()
ECMAScript v3
.slice(, )
, .
, .
, 1 , 2 . .
,
. ,
, , .
, .
, ,
, , , .
slice() , , .
, ,
621
Array.sort()
, , .
, ,
, .
: slice() .
Array.splice().
var a = [1,2,3,4,5];
a.slice(0,3); //
a.slice(3);
//
a.slice(1,1); //
a.slice(3,2); //
[1,2,3]
[4,5]
[2,3,4]
[3]; IE 4 , [1,2,3]
Internet Explorer 4 .
IE .
Array.splice()
Array.sort()
ECMAScript v1
.sort()
.sort(orderfunc)
orderfunc
, .
. : ,
.
sort() .
sort() ,
(, ,
). , ,
.
,
, ,
.
, a b, :
,
a b
b.
, a b .
, a b.
622
Array.splice()
,
. ,
: orderfunc.
, ,
, :
//
function numberorder(a, b) { return a b; }
a = new Array(33, 4, 1111, 222);
a.sort();
// : 1111, 222, 33, 4
a.sort(numberorder); // : 4, 33, 222, 1111
Array.splice()
ECMAScript v3
.splice(, _, , ...)
, .
_
, , c
, , .
. , splice()
, , .
, ...
, ,
, .
, , .
splice() , ,
, ,
, . ,
,
. ,
, slice(), splice() .
splice() :
var a = [1,2,3,4,5,6,7,8]
a.splice(4);
// [5,6,7,8]; a [1,2,3,4]
a.splice(1,2);
// [2,3]; a [1,4]
623
Array.toLocaleString()
a.splice(1,1);
// [4]; [1]
a.splice(1,0,2,3); // []; [1 2 3]
Array.slice()
Array.toLocaleString()
ECMAScript v1
Object.toLocaleString()
.toLocaleString()
.
TypeError
, .
toLocaleString()
. toLocaleString()
, .
Array.toString(), Object.toLocaleString()
Array.toString()
ECMAScript v1
Object.toString()
.toString()
.
TypeError
, .
toString() .
, JavaScript
.
toString().
toString() ( to
String()). ,
. ,
join() .
Array.toLocaleString(), Object.toString()
624
Array.unshift()
Array.unshift()
ECMAScript v3
.unshift(, ...)
, ...
, .
.
unshift() ,
. shift()
,
. . : unshift() ,
.
unshift() shift(). :
var a = [];
a.unshift(1);
a.unshift(22);
a.shift();
a.unshift(33,[4,5]);
//
//
//
//
//
a:[]
a:[1]
a:[22,1]
a:[1]
a:[33,[4,5],1]
:
:
:
:
1
2
22
3
Array.shift()
Boolean
ECMAScript v1
ObjectBoolean
new Boolean() //
Boolean()
//
, Boolean
.
( new) Boolean()
Boolean, .
( new) Boolean()
.
625
Boolean.toString()
toString()
"true" "false" ,
Boolean.
valueOf()
, Boolean.
JavaScript. Boolean
. Boolean
toString(),
. toString()
( JavaScript ), JavaScript
Boolean,
toString().
Object
Boolean.toString()
ECMAScript v1
Object.toString()
b.toString()
"true" "false" , b:
Boolean.
TypeError
, Boolean.
Boolean.valueOf()
Boolean
ECMAScript v1
Object.valueOf()
b.valueOf()
, b,
Boolean.
TypeError
, Boolean.
626
Date
Date
ECMAScript v1
ObjectDate
new Date()
new Date()
new Date(_)
new Date(, , , , , , )
Date() Date ,
.
,
, , getTime().
,
, Date.parse(). ,
,
. , ,
. :
, UTC (Universal Coordinated Time
), GMT (Greenwich Mean Time
). Date.UTC().
Date() ( new).
Date() .
1 1970
(UTC). , 5000, ,
1 1970 .
_
, () .
, Date.parse().
. , 2001 2001 .
JavaScript 1900,
0 99.
, 0 () 11 ().
, 1 31. ,
1, 0.
.
, 0 () 23 (11 ).
.
, 0 59. .
Date
627
, 0 59.
.
, 0 999.
.
Date ;
.
Date : ,
(UTC GMT). "UTC",
.
. , get[UTC]Day()
: getDay() getUTCDay().
Date Date
TypeError, .
get[UTC]Date()
Date
.
get[UTC]Day()
Date
.
get[UTC]FullYear()
.
get[UTC]Hours()
Date .
get[UTC]Milliseconds()
Date
.
get[UTC]Minutes()
Date .
get[UTC]Month()
Date .
get[UTC]Seconds()
Date .
getTime()
() Date.
: , ,
getUTCTime() .
getTimezoneOffset()
. : ,
.
628
Date
getYear()
Date. ,
getFullYear().
set[UTC]Date()
Date
.
set[UTC]FullYear()
(, , ) Date
.
set[UTC]Hours()
(, , , ) Date
.
set[UTC]Milliseconds()
Date
.
set[UTC]Minutes()
(, , ) Date
.
set[UTC]Month()
(, , ) Date
.
set[UTC]Seconds()
(, , ) Date
.
setTime()
Date .
setYear()
Date. ,
setFullYear().
toDateString()
, Date .
toGMTString()
Date , GMT.
, toUTCString().
toLocaleDateString()
, Date
.
toLocaleString()
Date
.
toLocaleTimeString()
, Date
.
Date
629
toString()
Date .
toTimeString()
, Date .
toUTCString()
Date , .
valueOf()
Date .
Date
. Date(),
Date:
Date.parse()
.
Date.UTC()
UTC.
, Date:
d = new Date(); //
document.write(': "+d.toLocaleDateString() + '. ');//
document.write(': '+ d.toLocaleTimeString());
//
var dayOfWeek = d.getDay();
//
var weekend = (dayOfWeek == 0) || (dayOfWeek == 6);
// ?
Date
.
:
630
Date.getDate()
<script language="JavaScript">
today = new Date();
//
christmas = new Date(); //
christmas.setMonth(11); // ...
christmas.setDate(25); // 25
// ,
// ,
if (today.getTime() < christmas.getTime()) {
difference = christmas.getTime() today.getTime();
difference = Math.floor(difference / (1000 * 60 * 60 * 24));
document.write(' ' + difference + ' !<p>');
}
</script>
// ... HTML ...
<script language="JavaScript">
// Date
// 1000
now = new Date();
document.write('<p> ' +
(now.getTime()today.getTime())/1000 +
'.');
</script>
Date.parse(), Date.UTC()
Date.getDate()
ECMAScript v1
.getDate()
, Date,
.
1 31.
Date.getDay()
ECMAScript v1
.getDay()
, Date,
. 0 () 6 ().
Date.getFullYear()
.getFullYear()
ECMAScript v1
Date.getHours()
631
, , .
, .
Date.getHours()
ECMAScript v1
Date
.getHours()
, Date,
. 0 () 23
(11 ).
Date.getMilliseconds()
ECMAScript v1
Date
.getMilliseconds()
, Date,
.
Date.getMinutes()
ECMAScript v1
Date
.getMinutes()
, Date,
. 0 59.
Date.getMonth()
ECMAScript v1
Date
.getMonth()
, Date,
. 0 ()
11 ().
632
Date.getSeconds()
Date.getSeconds()
ECMAScript v1
Date
.getSeconds()
, Date,
. 0 59.
Date.getTime()
ECMAScript v1
.getTime()
, Date,
. . 01.01.1970 /,
.
getTime() . ,
Date ,
. :
, getUTCTime(), .
getTime() getDay() getDate(),
.
Date.parse() Date.UTC()
, Date.
Date.getTimezoneOffset()
ECMAScript v1
GMT
.getTimezoneOffset()
(GMT) .
getTimezoneOffset()
, , JavaScript
( ) .
, ,
, .
Date.getUTCDate()
Date.getUTCDate()
633
ECMAScript v1
( )
.getUTCDate()
( 1 31),
.
Date.getUTCDay()
ECMAScript v1
( )
.getUTCDay()
, , .
0 () 6 ().
Date.getUTCFullYear()
ECMAScript v1
( )
.getUTCFullYear()
, , .
, .
Date.getUTCHours()
ECMAScript v1
Date ( )
.getUTCHours()
, .
0 () 23 (11 ).
Date.getUTCMilliseconds()
Date ( )
.getUTCMilliseconds()
, .
ECMAScript v1
634
Date.getUTCMinutes()
Date.getUTCMinutes()
ECMAScript v1
Date ( )
.getUTCMinutes()
. 0 59.
Date.getUTCMonth()
ECMAScript v1
( )
.getUTCMonth()
, , .
0 () 11 (). : Date
1, 0.
Date.getUTCSeconds()
ECMAScript v1
Date ( )
.getUTCSeconds()
. 0 59.
Date.getYear()
Date ( )
.getYear()
, Date,
1900.
Date.parse()
/
Date.parse()
ECMAScript v1
635
Date.setDate()
, .
/ 1
1970 .
Date.parse() Date.
Date Date.parse(), Date .parse().
Date.parse() , ,
, ,
Date
Date Date.setTime().
ECMAScript ,
Date.parse(), , ,
Date.toString() Date.toUTCString(). ,
,
, JavaScript.
Date.setDate()
ECMAScript v1
.setDate(_)
_
1 31, (
) _ .
. ECMAScript
.
Date.setFullYear()
ECMAScript v1
, ,
.setFullYear()
.setFullYear(, )
.setFullYear(, , )
, , .
, , 1999;
, 99.
636
Date.setHours()
0 11,
( ) .
1 31,
( ).
.
Date.setHours()
ECMAScript v1
, , Date
.setHours()
.setHours(, )
.setHours(, , )
.setHours(, , , )
0 () 23 (11 ) ,
.
0 59,
( ).
ECMAScript.
0 59.
( ).
ECMAScript.
0 999,
( ).
ECMAScript.
. ECMAScript
.
Date.setMilliseconds()
Date
.setMilliseconds()
ECMAScript v1
Date.setMinutes()
637
, , .
0 999.
.
Date.setMinutes()
ECMAScript v1
, Date
.setMinutes()
.setMinutes(, )
.setMinutes(, , )
0 59, (
) , Date.
0 59,
( ).
ECMAScript.
0 999, (
) .
ECMAScript.
. ECMAScript
.
Date.setMonth()
ECMAScript v1
Date
.setMonth()
.setMonth(, )
0 () 11 (),
, Date,
. : , 0, 1.
638
Date.setSeconds()
1 31,
( ).
ECMAScript.
. ECMAScript
.
Date.setSeconds()
ECMAScript v1
Date
.setSeconds()
.setSeconds(, )
0 59, ,
Date.
0 999,
( ).
ECMAScript.
. ECMAScript
.
Date.setTime()
ECMAScript v1
.setTime()
/
1 1970 .
Date() Date.UTC()
Date.parse().
.
. ECMAScript .
Date.setUTCDate()
Date.setUTCDate()
639
ECMAScript v1
( )
.setUTCDate(_)
_
, .
1 31.
.
Date.setUTCFullYear()
ECMAScript v1
, ( )
.setUTCFullYear()
.setUTCFullYear(, )
.setUTCFullYear(, , )
, , .
, , 1999, , 99.
0 11,
( ). :
, 0, 1.
1 31, (
) .
.
Date.setUTCHours()
, ,
( )
.setUTCHours()
.setUTCHours(, )
.setUTCHours(, , )
.setUTCHours(, , , )
ECMAScript v1
640
Date.setUTCMilliseconds()
, , .
0 () 23 (11 ).
0 59,
( ).
0 59,
( ).
0 999,
( ).
.
Date.setUTCMilliseconds()
ECMAScript v1
Date ( )
.setUTCMilliseconds()
, ,
. 0 999.
.
Date.setUTCMinutes()
ECMAScript v1
, ( )
.setUTCMinutes()
.setUTCMinutes(, )
.setUTCMinutes(, , )
, , .
0 59.
0 59,
( ).
Date.setUTCMonth()
641
0 999, (
) .
.
Date.setUTCMonth()
ECMAScript v1
( )
.setUTCMonth()
.setUTCMonth(, )
, , .
0 () 11 (). :
, 0, 1.
1 31,
( ).
.
Date.setUTCSeconds()
ECMAScript v1
( )
.setUTCSeconds()
.setUTCSeconds(, )
, , .
0 59.
0 999,
( ).
.
642
Date.setYear()
Date.setYear()
ECMAScript v1; ECMAScript v3
Date
.setYear()
, ( )
, Date.
0 99, 1900, 1900
1999.
. ECMAScript
.
setYear() Date,
1900 1999 .
ECMAScript v3
JavaScript; setFullYear().
Date.toDateString()
ECMAScript v3
Date
.toDateString()
(
), , Date,
.
.
Date.toLocaleDateString(), Date.toLocaleString(), Date.toLocaleTimeString(), Date.to
String(), Date.toTimeString()
Date.toGMTString()
Date
.toGMTString()
, ,
Date.
.
Date.toLocaleDateString()
643
toGMTString() ,
Date.toUTCString().
ECMAScript v3 JavaScript
; toUTCString().
Date.toUTCString()
Date.toLocaleDateString()
ECMAScript v3
Date
.toLocaleDateString()
(
) ,
.
.
Date.toDateString(), Date.toLocaleString(), Date.toLocaleTimeString(), Date.toString(),
Date.toTimeString()
Date.toLocaleString()
ECMAScript v1
.toLocaleString()
, .
.
toLocaleString()
.
,
. toLocaleString() ,
.
.
Date.toLocaleDateString(), Date.toLocaleTimeString(), Date.toString(), Date.toUTCString()
Date.toLocaleTimeString()
Date
.toLocaleTimeString()
ECMAScript v3
644
Date.toString()
,
.
.
Date.toDateString(), Date.toLocaleDateString(), Date.toLocaleString(), Date.toString(),
Date.toTimeString()
Date.toString()
Date
ECMAScript v1
Object.toString()
.toString()
.
toString()
. toUTCString(), toString()
. toLocaleString(), toString()
.
.
Date.parse(), Date.toDateString(), Date.toLocaleString(), Date.toTimeString(), Date.to
UTCString()
Date.toTimeString()
ECMAScript v3
Date
.toTimeString()
,
, .
.
Date.toString(), Date.toDateString(), Date.toLocaleDateString(), Date.toLocaleString(),
Date.toLocaleTimeString()
Date.toUTCString()
Date ( )
.toUTCString()
ECMAScript v1
645
Date.UTC()
,
.
toUTCString() ,
.
Date.toLocaleString(), Date.toString()
Date.UTC()
ECMAScript v1
Date.UTC(, , , , , , )
. 0 99,
1900, 1900 1999.
, 0 () 11 ().
, 1 31. :
1, 0.
.
, 0 () 23 (11 ).
.
, 0 59.
.
, 0 59.
.
. ;
ECMAScript.
.
1 1970
.
Date.UTC() ,
Date(), Date.
646
Date.valueOf()
Date.UTC() UTC.
UTC ,
Date() Date.setTime().
Date() ,
, Date.UTC(). , Date()
, Date.UTC() (GMT).
Date, UTC, :
d = new Date(Date.UTC(1996, 4, 8, 16, 30));
Date.valueOf()
Date
ECMAScript v1
Object.valueOf()
.valueOf()
.
, Date.getTime().
decodeURI()
ECMAScript v3
URI
decodeURI(uri)
uri
, URI (Uniform Resource Identifier
) ,
.
uri,
, .
URIError
, uri
.
decodeURI() ,
uri. , encodeURI();
. .
.
decodeURIComponent(), encodeURI(), encodeURIComponent(), escape(), unescape()
647
decodeURIComponent()
decodeURIComponent()
ECMAScript v3
URI
decodeURIComponent(s)
s
, URI ,
.
s,
.
URIError
,
s .
decodeURIComponent() ,
s. , en
codeURIComponent; . .
encodeURI()
ECMAScript v3
URI
encodeURI(uri)
uri
, URI , .
uri,
.
URIError
, uri Unicode
.
encodeURI() ,
uri. ,
ASCII:
648
encodeURIComponent()
_ . ! ~ * ' ( )
encodeURI() URI ,
, URI , :
; / ? : @ & = + $ , #
uri
UTF8
%xx.
ASCII %xx,
\u0080 \u07ff ,
16 Unicode .
URI ,
URI (, )
URI, ? #.
, en
codeURIComponent().
decodeURI() , .
ECMAScript v3 escape() unescape(),
, .
// http://www.isp.com/app.cgi?arg1=1&arg2=hello%20world
encodeURI("http://www.isp.com/app.cgi?arg1=1&arg2=hello world");
encodeURI("\u00a9"); // %C2%A9
.
decodeURI(), decodeURIComponent(), encodeURIComponent(), escape(), unescape()
encodeURIComponent()
ECMAScript v3
URI
encodeURIComponent(s)
, URI , .
s,
.
URIError
, s Unicode
.
encodeURIComponent() ,
s. ,
ASCII:
649
Error
_ . ! ~ * ' ( )
, , /, :, #,
URI,
.
. , encodeURI().
encodeURIComponent() encodeURI():
encodeURIComponent() , URI (
, , ).
, URI.
Error
ECMAScript v3
ObjectError
new Error()
new Error()
,
.
Error. , Error
message;
,
. Error() (
new), , new.
message
,
. , ,
, .
name
, . Error
,
.
toString()
, ,
Error.
650
Error.message
Error
throw try/catch. name ,
message
.
JavaScript Error.
Error, SyntaxError
RangeError.
Error
.
: ECMAScript Error
toString() ( Error), ,
, message.
, toString() Error , .
,
name message Error.
:
function factorial(x) {
if (x < 0) throw new Error("factorial: x >= 0");
if (x <= 1) return 1; else return x * factorial(x1);
}
,
( Window.alert()):
try { &*(&/* */ }
catch(e) {
if (e instanceof Error) { // Error ?
alert(e.name + ": " + e.message);
}
}
.
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
Error.message
ECMAScript v3
error.message
651
Error.name
Error.name
ECMAScript v3
error.name
Error.toString
Error
ECMAScript v3
Object.toString()
error.toString()
, . ECMAScript
, ,
. , ,
.
escape()
escape(s)
, (
).
s,
.
escape() , ,
s. s .
escape() , s, ,
(@, *, _, +, , . /) ASCII
%xx %uxxxx ( x
). Unicode \u0000 \u00ff
%xx, Unicode %uxxxx.
, escape(), unescape().
652
eval()
escape() ECMAScript,
ECMAScript v3. ECMAScript
, . escape()
encodeURI() encodeURIComponent().
encodeURI(), encodeURIComponent()
eval()
ECMAScript v1
JavaScript#
eval()
, .
, , .
SyntaxError
, JavaScript.
EvalError
, eval() ,
, eval.
, .
JavaScript, eval(), , eval()
.
eval() , ,
JavaScript. JavaScript, eval
. Java
Script, eval() (
), .
, eval() undefined. ,
, eval() .
eval() JavaScript ,
.
,
JavaScript JavaScript.
JavaScript JavaScript,
,
653
EvalError
. eval() .
,
. ,
eval() String .
ECMAScript v3
eval() . ECMAScript
EvalError, eval
eval() .
eval("1+2"); // 3
// JavaScript
// .
// . Window.alert()
// Window.prompt().
try {
alert(": " + eval(prompt(" :","")));
}
catch(exception) {
alert(exception);
}
var myeval = eval; // EvalError
myeval("1+2");
// EvalError
EvalError
, eval()
ECMAScript v3
ObjectErrorEvalError
new EvalError()
new EvalError()
,
. ,
message EvalError.
EvalError. , Error
message;
,
. EvalError() (
new), , new.
message
,
. , ,
, . .
Error.message.
654
Function
name
, . EvalError
"EvalError".
EvalError , eval()
.
eval() .
, Error.
Function
JavaScript
ECMAScript v1
ObjectFunction
function _(__) //
{
}
function(__) { }
//
_(__)
//
new Function(_..., )
_...
,
Function.
, . Java
Script, ,
, .
Function. Java
Script, .
SyntaxError
, _
JavaScript.
arguments[]
, . .
655
Function.apply()
caller
Function, , null,
. .
length
, .
prototype
, ,
, .
apply()
,
.
call()
, .
toString()
.
JavaScript . 8
, , 9
, , .
. . :
Function(), ,
.
JavaScript 1.1
arguments, Arguments.
,
. arguments[], .
. Arguments.
Arguments; 8 9
Function.apply()
ECMAScript v3
.apply(_, )
_
, .
_ this.
null, .
656
Function.arguments[]
, .
, .
TypeError
, , ,
, Arguments.
apply() , ,
_, ,
. , .
this _.
Arguments.
, ,
Function.call().
// Object.toString(), ,
// .
// .
Object.prototype.toString.apply(o);
// Math.max(),
// . :
// .
var data = [1,2,3,4,5,6,7,8];
Math.max.apply(null, data);
Function.call()
Function.arguments[]
.arguments[i]
.arguments.length
arguments Function ,
. .
arguments.length .
,
Arguments. ECMAScript v1 Function.arguments,
ECMAScript v3 .
, JavaScript.
Arguments
657
Function.call()
Function.call()
ECMAScript v3
.call(_, ...)
_
, .
_ this.
null, .
...
, .
, .
TypeError
, , .
call() , ,
_, ,
_. call() ,
. this
_ , _
null.
,
Function.apply().
// Object.toString(), ,
// .
// .
Object.prototype.toString.call(o);
Function.apply()
Function.caller
.caller
658
Function.length
(. . caller
, ).
Function.caller ECMAScript
. .
Function.length
ECMAScript v1
.length
length ,
.
. Function
length Arguments, ,
. Arguments.length.
Arguments.length
Function.prototype
ECMAScript v1
.prototype
prototype , .
, .
, , ,
prototype.
, prototype JavaScript
9.
Function.toString()
ECMAScript v1
.toString()
, .
TypeError
, , .
getClass()
659
toString() Function ,
. , Firefox IE,
JavaScript, function,
, . .
toString() eval().
.
getClass()
LiveConnect
JavaClass JavaObject
getClass(_java)
_java
JavaObject.
JavaClass JavaObject (_java).
getClass() , JavaObject
(_java) JavaClass JavaObject, . .
JavaClass, Java Java,
JavaObject.
JavaScript getClass() getClass,
Java. JavaScript JavaObject
Java java.lang.Class.
Java Rectangle, :
var r = new java.awt.Rectangle();
r JavaScript, JavaObject.
JavaScript getClass() JavaClass,
java.awt.Rectangle:
var c = getClass(r);
, JavaClass java.awt.Rectangle:
if (c == java.awt.Rectangle) ...
Java getClass() :
c = r.getClass();
c JavaObject,
java.lang.Class.
Java java.awt.Rectangle. ja
va.lang.Class Java.
660
Global
, ,
true Java o:
(getClass(o.getClass()) == java.lang.Class)
Global
ECMAScript v1
ObjectGlobal
this
,
.
undefined undefined, Global.
undefined. ,
.
Infinity
, .
java
JavaPackage, java.* .
NaN
.
undefined
undefined.
,
,
. , parseInt()
parseInt(), Global.parseInt().
decodeURI()
, encodeURI().
decodeURIComponent()
, encodeURIComponent().
encodeURI
URI,
.
encodeURIComponent
URI,
.
escape()
,
.
Global
661
eval()
JavaScript .
getClass()
JavaClass JavaObject.
isFinite()
, .
isNaN
, (NaN).
parseFloat()
.
parseInt()
.
unescape()
, escape().
,
,
JavaScript. ,
, Math,
, .
Array
Array().
Boolean
Boolean().
Date
Date().
Error
Error().
EvalError
EvalError().
Function
Function().
Math
, .
Number
Number().
Object
Object().
RangeError
RangeError().
662
Global
ReferenceError
ReferenceError().
RegExp
RegExp().
String
String().
SyntaxError
SyntaxError().
TypeError
TypeError().
URIError
URIError().
, JavaScript
.
, .
, . (
,
Global.) JavaScript
this.
, . .
,
. JavaS
cript , , parseInt(), par
seInt . ,
, , ,
JavaScript , .
, . Global()
.
JavaScript ,
, .
ECMAScript ,
JavaScript ,
.
, JavaScript,
Java LiveConnect ,
java Packages,
getClass(). JavaScript Window,
, JavaScript.
JavaScript
,
for/in:
var variables = ""
for(var name in this)
variables += name + "\n";
663
Infinity
Window (. IV ); 4
Infinity
ECMAScript v1
Infinity
Infinity , ,
. Infinity
for/in delete.
, Infinity
, . ( Number.POSITIVE_IN
FINITY .)
isFinite()
ECMAScript v1
isFinite(n)
n ( ) true,
n (NaN) / false.
.
Infinity, isNaN(), NaN, Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY
isNaN()
ECMAScript v1
isNaN(x)
x (
) true, x false.
isNaN() , ,
(NaN), . . (,
664
java
). , . . NaN , ,
false, NaN, ==
===, .
isNaN() ,
parseFloat() parseInt(), ,
. isNaN()
, .
isNaN(0);
isNaN(0/0);
isNaN(parseInt("3"));
isNaN(parseInt("hello"));
isNaN("3");
isNaN("hello");
isNaN(true);
isNaN(undefined);
//
//
//
//
//
//
//
//
false
true
false
true
false
true
false
true
java
LiveConnect
JavaPackage, java.*
java
JavaScript, LiveConnect
Java, java
JavaPackage, java.*.
, , , java.util Java
java.util. Java, java.*,
. Property.
JavaPackage, Packages; 12
JavaArray
LiveConnect
Java# JavaScript
_java.length //
_java[index] //
length
,
Java, JavaArray.
665
JavaClass
: Java Java
Script. , Java
. length JavaArray
. , Java
(. .
).
JavaScript .
<
=
<
=
p.xpoints.length; i++)
Math.round(Math.random()*100);
p.ypoints.length; i++)
Math.round(Math.random()*100);
JavaClass
LiveConnect
Java# JavaScript
_java.static_member //
// Java
new _java(...)
// Java
JavaClass ,
Java,
.
. JavaClass
; JavaClass
for/in.
666
JavaObject
, Java .
,
.
JavaScript
. .
, :
var version = java.lang.System.getProperty("java.version");
, JavaClass Java:
var java_date = new java.lang.Date();
JavaObject
Java# JavaScript
_java. // /
LiveConnect
667
JavaObject
JavaObject ,
(
) Java.
.
, JavaObject,
Java.
JavaObject for/in.
, Java .
, ,
. , width java.awt.
Rectangle , Java
Script .
r,
:
var perimeter = 2*r.width + 2*r.height;
,
r JavaScript:
r.width = perimeter/4;
r.height = perimeter/4;
668
JavaPackage
JavaPackage
LiveConnect
Java# JavaScript
._
._
// JavaPackage
// JavaClass
JSObject
. JSObject IV
Math
Math.
Math.()
ECMAScript v1
Math
Math.E
e, .
Math.LN10
10.
Math.LN2
2.
Math.LOG10E
e.
Math.LOG2E
e 2.
Math.PI
?.
Math.SQRT1_2
, 2.
Math.SQRT2
2.
Math.abs()
.
Math.acos()
.
Math.asin()
.
Math.atan()
.
Math.atan2()
X .
Math.ceil()
.
Math.cos()
.
Math.exp()
e.
Math.floor()
.
Math.log()
.
Math.max()
.
669
670
Math.abs()
Math.min()
.
Math.pow()
x y.
Math.random()
.
Math.round()
.
Math.sin()
.
Math.sqrt()
.
Math.tan()
.
Math , ,
.
:
y = Math.sin(x);
area = radius * radius * Math.PI;
Number
Math.abs()
ECMAScript v1
Math.abs(x)
x.
Math.acos()
Math.acos(x)
1,0 1,0.
ECMAScript v1
Math.asin()
671
x.
0 .
Math.asin()
ECMAScript v1
Math.asin(x)
1,0 1,0.
x.
/2 /2 .
Math.atan()
ECMAScript v1
Math.atan(x)
x.
/2 /2 .
Math.atan2()
ECMAScript v1
Math.atan2(y, x)
Y .
X .
, ,
, X (x,y).
Math.atan2() y/x. y
Y ( ) , x X
( ) .
: Y X.
672
Math.ceil()
Math.ceil()
ECMAScript v1
Math.ceil(x)
, x.
Math.ceil() , . .
, . Math.ceil()
Math.round() , , .
, Math.ceil()
;
.
a
b
c
d
=
=
=
=
Math.ceil(1.99);
Math.ceil(1.01);
Math.ceil(1.0);
Math.ceil(1.99);
//
//
//
//
Math.cos()
2.0
2.0
1.0
1.0
ECMAScript v1
Math.cos(x)
. ,
0,017453293 (2/360).
x.
1,0 1,0.
Math.E
ECMAScript v1
Math.E
Math.E e, ,
2,71828.
673
Math.exp()
Math.exp()
ECMAScript v1
Math.exp(x)
, .
ex e, x, e
, 2,71828.
Math.floor()
ECMAScript v1
Math.floor(x)
, x.
, ,
, .
Math.floor() ,
Math.round(), . :
Math.floor() (. . ),
(. . ).
a
b
c
d
=
=
=
=
Math.floor(1.99);
Math.floor(1.01);
Math.floor(1.0);
Math.floor(1.01);
//
//
//
//
Math.LN10
1.0
1.0
1.0
2.0
ECMAScript v1
loge10
Math.LN10
674
Math.LN2
Math.LN2
ECMAScript v1
loge2
Math.LN2
Math.LN2 loge2, 2. ,
0,69314718055994528623.
Math.log()
ECMAScript v1
Math.log(x)
, .
x.
Math.log() .
.
10 2 :
log10x = log10e logex
log2x = log2e logex
JavaScript:
function log10(x) { return Math.LOG10E * Math.log(x); }
function log2(x) { return Math.LOG2E * Math.log(x); }
Math.LOG10E
ECMAScript v1
log10e
Math.LOG10E
Math.LOG10E log10e, 10 e.
0,43429448190325181667.
Math.LOG2E
log2e
Math.LOG2E
ECMAScript v1
Math.max()
675
Math.LOG2E log2e, 2 e.
1,442695040888963387.
Math.max()
Math.max(...)
...
. ECMAScript v3
.
. Infinity, .
NaN, NaN ,
.
Math.min()
Math.min(...)
...
. ECMAScript v3
.
. Infinity, .
NaN, NaN
.
Math.PI
ECMAScript v1
Math.PI
Math.PI , . . .
, 3,14159265358979.
676
Math.pow()
Math.pow()
ECMAScript v1
Math.pow(x, y)
x
y
, .
, x.
x y (xy).
Math.pow() x y. x y .
, Math.pow() NaN.
, x , y
. ,
Infinity.
Math.random()
ECMAScript v1
Math.random()
0,0 1,0.
Math.round()
ECMAScript v1
Math.round(x)
x .
, x.
Math.round() . 0,5
. , 2,5 3, 2,5 2.
Math.sin()
Math.sin(x)
ECMAScript v1
Math.sqrt()
677
.
0,017453293 (2/360).
x 1,0 1,0.
Math.sqrt()
ECMAScript v1
Math.sqrt(x)
, 0.
x. NaN, x .
Math.sqrt() . ,
Math.pow(). :
Math.cuberoot = function(x){ return Math.pow(x,1/3); }
Math.cuberoot(8); // 2
Math.SQRT1_2
ECMAScript v1
1/2
Math.SQRT1_2
Math.SQRT1_2 1/2, , 2.
0,7071067811865476.
Math.SQRT2
ECMAScript v1
Math.SQRT2
Math.SQRT2 2, 2. ,
1,414213562373095.
678
Math.tan()
Math.tan()
ECMAScript v1
Math.tan(x)
, . ,
0,017453293 (2/360).
x.
NaN
ECMAScript v1
NaN
NaN ,
. NaN for/in
delete. : NaN ,
, .
, , isNaN(),
. . NaN ,
!
Number
ECMAScript v1
ObjectNumber
new Number()
Number()
Number ,
.
Number() ( new),
Number. Number()
( new),
( NaN,
).
Number
679
Number.MAX_VALUE
.
Number.MIN_VALUE
.
Number.NaN
.
Number.NEGATIVE_INFINITY
, .
Number.POSITIVE_INFINITY
; .
toString()
.
toLocaleString()
,
.
toFixed()
,
.
toExponential()
.
toPrecision()
,
.
.
valueOf()
Number.
JavaScript. JavaScript
Number,
. JavaScript
.
Number Number(),
.
Number() (
new).
( NaN), .
Number()
: ,
, .
680
Number.MAX_VALUE
:
Number(), . , MAX_VALUE
:
var biggest = Number.MAX_VALUE
:
var n = new Number(2);
Number.MAX_VALUE
ECMAScript v1
Number.MAX_VALUE
Number.MAX_VALUE , JavaScript.
1,79E+308.
Number.MIN_VALUE
ECMAScript v1
Number.MIN_VALUE
Number.MIN_VALUE ( ,
), JavaScript. 5E324.
Number.NAN
ECMAScript v1
Number.NaN
Number.NaN , ,
(,
Number.NEGATIVE_INFINITY
681
) . parseInt() parseFloat()
, ;
Number.NaN ,
, .
JavaScript Number.NaN NaN. :
NaN , NaN.
, , Number.NaN.
isNaN(). ECMAScript v1
Number.NaN
NaN.
isNaN(), NaN
Number.NEGATIVE_INFINITY
ECMAScript v1
Number.NEGATIVE_INFINITY
Number.NEGATIVE_INFINITY , ,
, JavaScript (. .
, Number.MAX_VALUE).
JavaScript NEGATIVE_INFINITY Infinity.
. , ,
, , , , .
ECMAScript v1
Infinity Number.NEGATIVE_INFINITY.
Infinity, isFinite()
Number.POSITIVE_INFINITY
ECMAScript v1
Number.POSITIVE_INFINITY
Number.POSITIVE_INFINITY , ,
, JavaScript
(. . Number.MAX_VALUE). :
, Number.MIN_VALUE, JavaScript
.
JavaScript POSITIVE_INFINITY Infinity.
, . , ,
, , , , .
682
Number.toExponential()
ECMAScript v1 Number.POSITIVE_INFINITY
Infinity.
Infinity, isFinite()
Number.toExponential()
ECMAScript v3
.toExponential()
. 0 20
,
. , , .
, , .
, , ,
.
RangeError
, .
0 20 RangeError.
.
TypeError
, ,
Number.
var n = 12345.6789;
n.toExponential(1);
n.toExponential(5);
n.toExponential(10);
n.toExponential();
//
//
//
//
1.2e+4
1.23457e+4
1.2345678900e+4
1.23456789e+4
.
Number.toFixed(), Number.toLocaleString(), Number.toPrecision(), Number.toString()
Number.toFixed()
.toFixed()
ECMAScript v3
683
Number.toLocaleString()
; 0 20
;
. , 0.
,
.
,
. , 1e+21, Number.to
String() .
RangeError
, .
0 20 RangeError.
.
TypeError
, ,
Number.
var n = 12345.6789;
n.toFixed();
//
//
n.toFixed(1);
//
n.toFixed(6);
//
//
(1.23e+20).toFixed(2); //
(1.23e10).toFixed(2) //
12346:
12345.7:
12345.678900:
123000000000000000000.00
0.00
.
Number.toExponential(), Number.toLocaleString(), Number.toPrecision(), Number. toString()
Number.toLocaleString()
ECMAScript v3
.toLocaleString()
,
, , ,
, .
TypeError
, , Number.
684
Number.toPrecision()
.
Number.toExponential(), Number.toFixed(), Number.toPrecision(), Number.toString()
Number.toPrecision()
ECMAScript v3
.toPrecision()
.
1 21 .
. ,
toString().
, ,
.
, .
1
. .
RangeError
, .
1 21 RangeError.
.
TypeError
, ,
Number.
var n = 12345.6789;
n.toPrecision(1); //
n.toPrecision(3); //
n.toPrecision(5); //
n.toPrecision(10); //
1e+4
1.23e+4
12346:
12345.67890:
.
Number.toExponential(), Number.toFixed(), Number.toLocaleString(), Number.toString()
Number.toString()
.toString()
ECMAScript v3
Object.toString()
685
Number.valueOf()
, ( 2
36), . ,
10. , ECMAScript
,
, 10.
.
TypeError
, ,
Number.
toString() Number .
10, 10.
, ECMAScript
,
2 36.
.
Number.toExponential(), Number.toFixed(), Number.toLocaleString(), Number.toPrecision()
Number.valueOf()
ECMAScript v1
Object.valueOf()
.valueOf()
Number.
.
TypeError
, ,
Number.
Object.valueOf()
Object
, JavaScript#
new Object()
new Object()
ECMAScript v1
686
Object
JavaScript
, ,
Number, Boolean String.
,
Object. ,
Number, Boolean String .
Object() ( new),
, new.
constructor
JavaScript, .
hasOwnProperty()
, ( )
.
isPrototypeOf()
, .
propertyIsEnumerable()
,
for/in.
toLocaleString()
.
toString(),
.
toString()
.
Object .
Object toString(),
.
valueOf()
, .
Object . Object,
Number Boolean, ,
, .
Object JavaScript.
JavaScript; ,
Object .
JavaScript 7.
687
Object.constructor
Object(),
,
7.
Object.constructor
ECMAScript v1
.constructor
constructor ,
. , a
Array(), a.constructor Array:
a = new Array(1,2,3); //
a.constructor == Array // true
constructor
. typeof ,
. ,
constructor , .
, , :
function isArray(x) {
return ((typeof x == "object") && (x.constructor == Array));
}
, ,
JavaScript, JavaScript,
Window, . Object.toString(),
, .
Object.toString()
Object.hasOwnProperty()
ECMAScript v3
.hasOwnProperty(_)
_
, .
true, ,
_. false,
.
688
Object.isPrototypeOf()
9 , JavaScript ,
. hasOwnProperty()
,
.
//
//
//
//
//
true: x o
false: o y
false: toString
Function.prototype, Object.propertyIsEnumerable(); 9
Object.isPrototypeOf()
ECMAScript v3
.isPrototypeOf(o)
true, o.
false, o
o.
9, JavaScript
. proto
type ,
. isPrototypeOf() ,
.
.
Function.prototype, Object.constructor; 9
Object.propertyIsEnumerable()
Object.propertyIsEnumerable()
689
ECMAScript v3
, for/in
.propertyIsEnumerable(_)
_
, .
true, ,
_, , . .
for/in .
for/in .
: ,
JavaScript, , (, )
. propertyIsEnumerable()
. : ECMAScript , property
IsEnumerable() , . .
.
Function.prototype, Object.hasOwnProperty(); 7
Object.toLocaleString()
ECMAScript v3
.toString()
.
,
. toLocale
String(), Object,
toString() .
690
Object.toString()
.
Array.toLocaleString(), Date.toLocaleString(), Number.toLocaleString(), Object.toString()
Object.toString()
ECMAScript v1
.toString()
, .
toString() , JavaScript
. ,
, .
JavaScript toString()
, . ,
, :
alert(my_object);
,
+:
var msg = ' : ' + my_object;
toString() .
,
, .
JavaScript ,
toString(). , toString(),
Object.
:
[object ]
,
. ,
Object.
Object.constructor.
691
Object.valueOf()
toString() JavaScript
.
toString() .
, toString() ,
, . ,
, JavaScript :
y = Math.sqrt(x);
//
ystr = y.toString(); //
,
toString(), .
toString()
, JavaScript .
toString() :
alert(my_obj.toString());
Object.valueOf()
ECMAScript v1
.valueOf()
, , .
, .
valueOf() ,
, . Object ,
.
Number valueOf()
, .
, Boolean, , String.
valueOf().
JavaScript , ,
. valueOf()
. typeof, ,
String, JavaScript
.
valueOf() Number, Boolean String
. Object()
,
:
. JavaScript
, Ob
ject() .
692
Packages
valueOf()
. , JavaScript
( ).
, . .
.
:
Complex.prototype.valueOf = new Function("return this.real");
valueOf() Complex, ,
, Math.sqrt(),
.
Object.toString()
Packages
LiveConnect
JavaPackage
Packages
JavaScript, LiveConnect
Java, Packages Java
Package,
Java. , Packages.javax.swing Java
javax.swing. java Packages.java.
java, JavaPackage; 12
parseFloat()
ECMAScript v1
parseFloat(s)
,
.
NaN, s
. JavaScript 1.0, s , parseFloat()
0 NaN.
parseFloat()
, s. , parse
Float() s , . s
, parseFloat() ,
693
parseInt()
(NaN).
isNaN(). ,
parseInt(), parseFloat().
isNaN(), parseInt()
parseInt()
ECMAScript v1
parseInt(s)
parseInt(s, )
,
. 0,
(
0x 0X) . 2 36, parseInt()
NaN.
(NaN, s ).
JavaScript 1.0, s, par
seInt() 0 NaN.
parseInt() s
( ), s.
, parseInt() s ,
. s
, parseInt(),
(NaN).
isNaN().
. , 10,
parseInt() . 8,
( 0 7), 16
( 0 9 A F).
2 36.
0 , parseInt()
s. s ( )
0x, parseInt() s
. s 0, ECMAScript v3
, .
s 1 9, parseInt() .
694
RangeError
parseInt("17", 8);
parseInt("1f", 16);
parseInt("10");
parseInt("0x10");
parseInt("010");
//
//
//
//
//
15 (8 + 7)
31 (16 + 15)
10
16
: 10, 8
, ECMAScript v3 ,
0 ( 0x 0X), ,
.
, ,
0x 0X.
isNaN(), parseFloat()
RangeError
,
ECMAScript v3
ObjectErrorRangeError
new RangeError()
new RangeError()
,
. ,
message RangeError.
RangeError. ,
RangeError message;
RangeError
, . RangeError(),
( new), ,
new.
message
,
. , ,
, .
. Error.message.
name
, . RangeError
"RangeError".
RangeError ,
. ,
695
ReferenceError
RangeError.
. Error.
ReferenceError
ECMAScript v3
ObjectErrorReferenceError
new ReferenceError()
new ReferenceError()
,
. ,
message ReferenceError.
ReferenceError. , Refe
renceError message;
, .
ReferenceError(), ( new),
, new.
message
,
. , ,
, .
. Error.message.
name
, . ReferenceError
"ReferenceError".
ReferenceError
.
. Error.
RegExp
//
ECMAScript v3
ObjectRegExp
696
RegExp
new RegExp(, )
,
.
, g, i m,
, .
ECMAScript m .
, , .
RegExp .
, ,
RegExp() RegExp, ,
RegExp. RegExp() ( new),
, new, ,
RegExp; ,
RegExp.
SyntaxError
,
, g, i m.
TypeError
, RegExp, .
global
RegExp g.
ignoreCase
RegExp i.
lastIndex
;
.
multiline
RegExp m.
source
.
exec()
.
test()
, .
697
RegExp.exec()
RegExp
.
11.
11
RegExp.exec()
ECMAScript v3
regexp.exec()
, .
, null,
. .
TypeError
, ,
RegExp.
698
RegExp.global
: exec()
, regexp
. exec() String.match(),
.
exec()
.
exec() :
var pattern = /\bJava\w*\b/g;
var text = "JavaScript is more fun than Java or JavaBeans!";
var result;
while((result = pattern.exec(text)) != null) {
alert("Matched `" + result[0] +
"' at position " + result.index +
" next search begins at position " + pattern.lastIndex);
}
.
RegExp.lastIndex, RegExp.test(), String.match(), String.replace(), String.search(); 11
RegExp.global
ECMAScript v3
regexp.global
global RegExp, .
, , . .
g.
RegExp.ignoreCase
ECMAScript v3
regexp.ignoreCase
ignoreCase RegExp, .
,
, . . i.
RegExp.lastIndex
regexp.lastIndex
ECMAScript v3
699
RegExp.source
lastIndex RegExp.
g ,
,
, RegExp.exec() RegExp.test().
.
. : lastIndex RegExp,
g .
,
, ,
. exec() test() lastIndex 0,
( ) .
,
0.
RegExp.exec(), RegExp.test()
RegExp.source
ECMAScript v3
regexp.source
source RegExp,
RegExp. ,
, g,
i m.
RegExp.test()
ECMAScript v3
regexp.test()
.
true, , regexp, false
.
TypeError
, ,
RegExp.
700
RegExp.toString()
test() , , ,
regexp. , true, false.
test() r s
:
(r.exec(s) != null)
.
RegExp.exec(), RegExp.lastIndex, String.match(), String.replace(), String.substring();
11
RegExp.toString()
ECMAScript v3
Object.toString()
regexp.toString()
regexp.
TypeError
, ,
RegExp.
RegExp.toString()
.
:
, ,
. ,
:
new RegExp("/", "g")
RegExp.toString() ///g
/\//g.
String
new String(s) //
String(s)
//
ECMAScript v1
ObjectString
String
701
, String
.
String() ( new),
String, s s.
String(), new, s
.
length
.
charAt()
, .
charCodeAt()
, .
concat()
.
indexOf()
.
lastIndexOf()
.
localeCompare()
.
match()
.
replace()
.
search()
, .
slice()
.
split()
.
substr()
. substring().
substring()
.
702
String
toLowerCase()
, .
toString()
.
toUpperCase()
, .
valueOf()
.
String.fromCharCode()
,
.
HTML
JavaScript String ,
, HTML.
ECMAScript,
HTML , JavaScript.
,
HTML ,
:
var s = " !";
var html = s.bold().link("javascript:alert('hello')").fontcolor("red");
,
:
anchor()
<a name=>.
big()
<big>.
blink()
<blink>.
bold()
<b>.
fixed()
<tt>.
fontcolor()
<font color=>.
fontsize()
<font size=>.
italics()
<i>.
link(url)
<a href=>.
703
String.charAt()
small()
<small>.
strike()
<strike>.
sub()
<sub>.
sup()
<sup>.
JavaScript. String
. length
String . String
. ,
.
: JavaScript ,
String, . , String.to
UpperCase(), , .
JavaScript, ,
Netscape (, , Firefox),
, . ,
s, s[2] s.charAt(2).
, for/in, ,
. ( , length
, ECMAScript.)
, .
String.charAt()
ECMAScript v1
n#
.charAt(n)
, .
n .
String.charAt() n .
. n 0 string.length1,
. : JavaScript ,
, 1.
704
String.charCodeAt()
String.charCodeAt()
ECMAScript v1
n#
.charCodeAt(n)
, .
Unicode n 16 0 65 535.
charCodeAt() charAt(), ,
, , ,
. n , charCodeAt()
NaN.
Unicode ,
String.fromCharCode().
String.charAt(), String.fromCharCode()
String.concat()
ECMAScript v3
.concat(, ...)
, ...
, .
, .
concat() ( )
. .
: .
String.concat() Array.concat(). ,
+.
Array.concat()
String.fromCharCode()
ECMAScript v1
705
String.indexOf()
, . ,
fromCharCode() String()
String.
String.charCodeAt(),
.
// "hello"
var s = String.fromCharCode(104, 101, 108, 108, 111);
String.charCodeAt()
String.indexOf()
ECMAScript v1
.indexOf()
.indexOf(, start)
, .
start
, ,
. 0 ( )
string.length1 ( ).
, .
, start,
, 1, .
String.indexOf() , ,
. start
, start . , String.indexOf()
.
.
, String.indexOf() 1.
706
.
String.lastIndexOf()
String.charAt(), String.lastIndexOf(), String.substring()
String.lastIndexOf()
ECMAScript v1
.lastIndexOf()
.lastIndexOf(, start)
, .
start
, ,
. : 0 ( )
.length1 ( ).
, .
, start,
, 1, .
String.lastIndexOf() , ,
. start
, start . , String.lastIndexOf()
.
, ,
start.
, String.lastIndexOf() 1.
: String.lastIndexOf() ,
.
0, .length1.
String.length
.length
String.length ,
. s
s.length1. length for/in
delete.
707
String.localeCompare()
String.localeCompare()
ECMAScript v3
.localeCompare(_)
_
,
.
, . _,
localeCompare() . _,
.
, 0.
< >,
Unicode; , ,
. , ,
. , , , ch
, d.
localeCompare() ,
. ECMAScript
, ;
, ,
.
, ,
:
var strings; // ;
strings.sort(function(a,b) { return a.localeCompare(b) });
String.match()
ECMAScript v3
.match(regexp)
regexp
RegExp, .
RegExp, RegExp().
, . ,
regexp g.
.
708
String.replace()
match() , regexp.
, g
regexp . 11.
regexp g, match() .
, match() null.
, .
0 . ,
.
. index
. , input
.
regexp g, match() ,
. null,
, , .
.
,
index input. : match()
,
.
RegExp.exec().
, , :
"1 plus 2 equals 3".match(/\d+/g) // ["1", "2", "3"]
, ,
.
URL, ,
URL:
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var text = "Visit my home page at http://www.isp.com/~david";
var result = text.match(url);
if (result != null) {
var fullurl = result[0]; // "http://www.isp.com/~david"
var protocol = result[1]; // "http"
var host = result[2];
// "www.isp.com"
var path = result[3];
// "~david"
}
.
RegExp, RegExp.exec(), RegExp.test(), String.replace(), String.search(); 11
String.replace()
(),
.replace(regexp, )
ECMAScript v3
709
String.replace()
regexp
RegExp, .
,
RegExp.
, , ,
. . .
, regexp
.
replace() .
, regexp,
. regexp
g, replace() .
.
, . ,
. , ,
$, .
, , ,
.
, regexp
$`
$'
$$
ECMAScript v3 , ,
.
, .
, , ,
. ,
. .
, ,
, .
JavaScript:
text.replace(/javascript/i, "JavaScript");
710
String.search()
:
text.replace(/"([^"]*)"/g, "``$1''");
:
text.replace(/\b\w+\b/g, function(word) {
return word.substring(0,1).toUpperCase() +
word.substring(1);
});
.
RegExp, RegExp.exec(), RegExp.test(), String.match(), String.search(); 11
String.search()
ECMAScript v3
.search(regexp)
regexp
RegExp, ,
. RegExp,
RegExp().
, regexp,
1, .
search() ,
regexp, 1,
.
, g.
regexp.lastIndex , ,
, .
.
RegExp, RegExp.exec(), RegExp.test(), String.match(), String.replace(); 11
String.slice()
.slice(start, end)
ECMAScript v3
711
String.split()
start
, .
, , . 1
, 2 . .
end
. , start
. , ,
.
, ,
start ( ) end ( ).
slice() , , ,
.
slice(), substring() substr() String
. slice() , substring(),
. slice() substr()
, , substr()
. , String.slice() Ar
ray.slice().
var s = "abcdefg";
s.slice(0,4) // "abcd"
s.slice(2,4) // "cd"
s.slice(4)
// "efg"
s.slice(3,1) // "def"
s.slice(3,2) // "de"
s.slice(3,1) // "ef"; IE 4 "abcdef"
Array.slice(), String.substring()
String.split()
.split(, )
, .
ECMAScript v3
712
String.split()
, .
,
. , .
, ,
.
, .
split() ,
.
, , ,
.
, , .
, ,
,
. , ,
( ) .
, ,
, .
,
, ,
, ,
. ( ,
.)
, , ,
, .
, ,
, ( ,
), .
String.split() Array.join().
split() :
"1:2:3:4:5".split(":"); // ["1","2","3","4","5"]
"|a|b|c|".split("|"); // ["", "a", "b", "c", ""]
split()
, :
var words = sentence.split(' ');
,
:
var words = sentence.split(/\s+/);
,
. ,
:
713
String.substr()
"hello".split("");
// ["h","e","l","l","o"]
"hello".split("", 3); // ["h","e","l"]
,
,
. , HTML
:
var text = "hello <b>world</b>";
text.split(/(<[^>]*>)/); // ["hello ","<b>","world","</b>",""]
Array.join(), RegExp; 11
String.substr()
JavaScript 1.2;
.substr(, )
. ,
, : 1 , 2
. .
. ,
.
, , (
); , , ,
.
substr() , .
: substr()
. String.
substring() String.splice(),
. , ECMAScript
, , .
var s = "abcdefg";
s.substr(2,2); // "cd"
s.substr(3);
// "defg"
s.substr(3,2); // "ef"; IE 4 "ab"
IE 4 (
IE ). ,
, 0.
String.slice(), String.substring()
714
String.substring()
String.substring()
ECMAScript v1
.substring(, )
, .
,
. ,
.
, .
, ,
1.
String.substring() ,
. ,
.
, ( 0). ,
, .
, ,
. ,
, ,
.
:
String.slice() String.substr().
, String.substring() .
.
String.charAt(), String.indexOf(), String.lastIndexOf(), String.slice(), String.substr()
String.toLocaleLowerCase()
ECMAScript v3
.toLocaleLowerCase()
,
. , ,
,
, toLowerCase().
715
String.toLocaleUpperCase()
String.toLocaleUpperCase()
ECMAScript v3
.toLocaleUpperCase()
,
. , ,
, ,
toUpperCase().
String.toLowerCase()
ECMAScript v1
.toLowerCase()
,
, .
String.toString()
ECMAScript v1
Object.toString()
.toString()
. .
TypeError
, ,
String.
String.valueOf()
String.toUpperCase()
.toUpperCase()
ECMAScript v1
716
String.valueOf()
,
, .
String.valueOf()
ECMAScript v1
Object.valueOf()
.valueOf()
.
TypeError
, ,
String.
String.toString()
SyntaxError
ECMAScript v3
ObjectErrorSyntaxError
new SyntaxError()
new SyntaxError()
,
. ,
message SyntaxError.
SyntaxError. , Syntax
Error message;
,
. SyntaxError(), (
new), , new.
message
,
. , ,
, . .
Error.message.
name
, . SyntaxError
"SyntaxError".
717
TypeError
SyntaxError JavaScript
. eval(), Function() RegExp()
. .
Error.
TypeError
ECMAScript v3
ObjectErrorTypeError
new TypeError()
new TypeError()
,
. ,
message TypeError.
TypeError. , TypeError
message;
,
. TypeError(), ( new),
, new.
message
,
. , ,
, . .
Error.message.
name
, . TypeError
"TypeError".
TypeError , ,
. null
.
, , , ,
, new
, . JavaScript
TypeError,
, .
Error.
718
undefined
undefined
ECMAScript v3
undefined
unescape()
unescape(s)
s.
unescape() , ,
escape(). s
%xx %uxxxx ( x
) Unicode \u00xx \uxxxx.
, unescape()
ECMAScript,
ECMAScript v3. ECMAScript ,
. decodeURI() decodeURI
Component(). . escape().
URIError
URI
new URIError()
new URIError()
ECMAScript v3
ObjectErrorURIError
719
URIError
,
. ,
message URIError.
URIError. , URIError
message;
,
. URIError(), ( new),
, new.
message
,
. , ,
, . .
Error.message.
name
, . URIError
1 "URIError".
JavaScript
,
, , JavaScript.
III .
:
Anchor
Applet
Attr
Canvas
CanvasGradient
CanvasPattern
CanvasRenderingContext2D
CDATASection
CharacterData
Comment
CSS2Properties
CSSRule
CSSStyleSheet
Document
DOMException
DOMImplementation
DOMParser
Element
Event
ExternalInterface
FlashPlayer
Form
Frame
History
HTMLCollection
HTMLDocument
HTMLElement
IFrame
JSObject
KeyEvent
Link
Location
MimeType
MouseEvent
Navigator
Node
NodeList
Option
Plugin
ProcessingInstruction
Range
RangeException
DocumentFragment
Image
Screen
DocumentType
Input
Select
Table
TableCell
TableRow
TableSection
Text
Textarea
UIEvent
Window
XMLHttpRequest
XMLSerializer
XPathExpression
XPathResult
XSLTProcessor
JavaScript
,
, , JavaScript.
III .
!
.
,
, . , submit()
Form, Form.submit, submit.
,
,
. ,
images[] HTMLDocument .
, ,
,
, . , cook
ie, HTMLDocument
HTMLDocument.cookie.
JavaScript ,
window, history alert(), Window,
Window.
, Window,
alert() Window.alert().
, .
, ,
. III
, ,
.
Anchor
DOM Level 0
NodeElementHTMLElementAnchor
String name
Anchor.
name <a>.
724
JavaScript
focus()
,
.
HTML
Anchor HTML <a>,
name:
<a name="name"> //
...
</a>
() HTML.
<a>, name. Document
anchors[], Anchor,
.
,
, hash Location #,
, focus()
Anchor.
: <a> .
HTML , JavaScript
Link, Anchor.
// "_bottom_"
document.anchors['_bottom_'].focus();
Anchor.focus()
DOM Level 0
void focus()
,
.
Applet
, #
document.applets[i]
document._
DOM Level 0
725
Attr
Applet
Java.
JSObject; JavaObject ; 12 23
Attr
726
JavaScript
Attr. HTML
Attr Text, value
.
XML XML ,
Text EntityReference,
.
XML
EntityReference ( ). ,
JavaScript value ,
.
,
Attr .
Element.getAttribute() Element.setAttribute().
, Attr
.
Element
Button
. Input
Canvas
HTML#
String height
1. ,
.
, , .
300.
String width
. ,
.
, , .
300.
getContext()
CanvasRenderingContext2D,
. "2d",
, .
Canvas , .
Canvas.getContext()
727
CanvasRenderingContext2D; 22
Canvas.getContext()
contextID
,
.
"2d", , ,
, API
.
CanvasRenderingContext2D,
Canvas.
, ,
. ,
( ).
"2d",
CanvasRenderingContext2D,
Canvas.
CanvasRenderingContext2D
CanvasGradient
Canvas
addColorStop()
.
728
CanvasGradient.addColorStop()
CanvasGradient ,
strokeStyle fillStyle CanvasRenderingContext2D. Canvas
Gradient createLinearGradient() createRadialGradient()
CanvasRenderingContext2D.
CanvasGradient addColorStop(),
,
. ,
.
.
.
CanvasRenderingContext2D.createLinearGradient(),CanvasRenderingContext2D.createRadial
Gradient()
CanvasGradient.addColorStop()
offset
0,0 1,0,
. 0
, 1 .
color
CSS, .
.
addColorStop()
. ,
, .
, .
, .
CanvasPattern
729
CanvasRenderingContext2D
CanvasRenderingContext2D.createPattern()
CanvasRenderingContext2D
,
730
CanvasRenderingContext2D
String shadowColor
CSS
, . "black".
Safari Firefox 1.5
Opera 9.
float shadowOffsetX, shadowOffsetY
.
, .
0. Safari
Firefox 1.5 Opera 9.
Object strokeStyle
, , .
CanvasGradient Can
vasPattern. ,
CSS, .
CanvasGradient CanvasPattern,
.
. CanvasRenderingContext2D.createLinearGradient(),
CanvasRenderingContext2D.createRadialGradient(),
CanvasRenderingContext2D.create
Pattern().
arc()
.
arcTo()
.
beginPath()
( )
.
bezierCurveTo()
.
clearRect()
.
clip()
.
closePath()
, .
createLinearGradient()
CanvasGradient, .
createPattern()
CanvasPattern,
.
CanvasRenderingContext2D
731
createRadialGradient()
CanvasGradient, .
drawImage()
.
fill()
, ,
fillStyle.
fillRect()
.
lineTo()
.
moveTo()
.
quadraticCurveTo()
.
rect()
.
restore()
.
rotate()
.
save()
, Canvas
RenderingContext2D.
scale()
.
stroke()
, .
lineWidth, lineJoin, lineCap strokeStyle.
strokeRect()
( ) .
translate()
.
CanvasRenderingContext2D
. , ,
,
. .
strokeRect()
fillRect(). , clearRect() .
732
CanvasRenderingContext2D
API Canvas Image,
HTML <img> ,
Image() (
Image). ,
Canvas.
Canvas drawImage(),
.
Canvas
, .
. Canvas
.
. Canvas '
.
.
:
, ,
.
,
.
moveTo();
, .
, , ,
Canvas .
,
stroke(),
fill(); .
: lineTo()
, rect() , arc() arcTo() ,
bezierCurveTo() quadraticCurveTo() .
. ,
.
clip() , ,
. ,
( ).
,
fill() clip() , ()
, .
, close
Path().
CanvasRenderingContext2D
733
,
,
,
fillStyle strokeStyle.
CSS, CanvasGradient Canvas
Pattern, .
createLinearGradient() createRadialGradient(),
createPattern().
CSS "#RRGGBB", RR, GG
BB , (red),
(green) (blue) 00 FF. ,
"#FF0000".
, "rgba(R, G, B, A)". R, G B
,
0 255, A ()
0,0 ( ) 1,0
( ). ,
"rgba(255, 0, 0, 0.5)".
,
Canvas .
lineWidth,
lineCap, lineJoin.
(0, 0),
, X ,
Y .
.
,
, .
translate(), scale() rotate(),
.
, ,
, lineTo(), .
API Canvas
, .
. ,
scale(), translate(),
, .
,
, . Canvas
. globalCompositeOpera
tion,
XOR ( ) ,
. CanvasRendering
Context2D.globalCompositeOperation,
.
734
CanvasRenderingContext2D.arc()
API Canvas ,
.
Safari .
shadowColor, shadowOffsetX sha
dowOffsetY. , shadowBlur
.
save() restore()
CanvasRenderingContext2D. save() ,
restore()
.
CanvasRenderingContext2D (
canvas, ).
, .
Canvas
CanvasRenderingContext2D.arc()
x, y
, .
radius
, .
startAngle, endAngle
, .
. 0.
.
counterclockwise
(true)
(false).
.
.
,
. ,
.
.
CanvasRenderingContext2D.arcTo()
735
.
CanvasRenderingContext2D.arcTo(),CanvasRenderingContext2D.beginPath(),CanvasRendering
Context2D.closePath()
CanvasRenderingContext2D.arcTo()
x1, y1
P1.
x2, y2
P2.
radius
, .
, ,
arc(). , ,
radius.
, P1,
, P1 P2.
.
P2, .
, .
.
:
c.moveTo(10,10);
//
c.lineTo(90, 10)
//
c.arcTo(100, 10, 100, 20, 10); //
c.lineTo(100, 100);
//
Firefox 1.5.
CanvasRenderingContext2D.arc()
736
CanvasRenderingContext2D.beginPath()
CanvasRenderingContext2D.beginPath()
Canvas
void beginPath()
beginPath()
. (0,0).
beginPath()
.
.
CanvasRenderingContext2D.closePath(), CanvasRenderingContext2D.fill(), CanvasRendering
Context2D.stroke(); 22
CanvasRenderingContext2D.bezierCurveTo()
cpX1, cpY1
,
( ).
cpX2, cpY2
,
.
x, y
bezierCurveTo()
Canvas. ,
x y.
(cpX1, cpY1) (cpX2, cpY2).
(x, y).
CanvasRenderingContext2D.quadraticCurveTo()
CanvasRenderingContext2D.clearRect()
CanvasRenderingContext2D.clip()
737
x, y
.
width, height
.
clearRect() ,
.
CanvasRenderingContext2D.clip()
void clip()
,
,
. : .
, save(),
restore() .
.
() .
CanvasRenderingContext2D.closePath()
void closePath()
, closePath() ,
, .
, . ,
.
, moveTo()
.
stroke() fill() closePath()
. (
clip()).
.
CanvasRenderingContext2D.beginPath(), CanvasRenderingContext2D.moveTo(), CanvasRender
ingContext2D.stroke(), CanvasRenderingContext2D.fill()
738
CanvasRenderingContext2D.createLinearGradient()
CanvasRenderingContext2D.createLinearGradient()
xStart, yStart
.
xEnd, yEnd
.
CanvasGradient, .
CanvasGradient,
.
: .
addColorStop() .
, Can
vasGradient strokeStyle fillStyle.
.
CanvasGradient.addColorStop(), CanvasRenderingContext2D.createRadialGradient()
CanvasRenderingContext2D.createPattern()
image
, .
Image, Canvas.
repetitionStyle
, .
:
"repeat"
.
"repeatx"
"repeaty"
"norepeat"
CanvasRenderingContext2D.createRadialGradient()
739
CanvasPattern, .
CanvasPattern, ,
.
, CanvasPattern
strokeStyle fillStyle.
CanvasPattern
CanvasRenderingContext2D.createRadialGradient()
xStart, yStart
.
radiusStart
.
xEnd, yEnd
radiusEnd
.
CanvasGradient, .
CanvasGradient,
.
: .
addColorStop() .
, CanvasGradient
strokeStyle fillStyle.
0
, 1
(, , )
.
.
CanvasGradient.addColorStop(), CanvasRenderingContext2D.createLinearGradient()
740
CanvasRenderingContext2D.drawImage()
CanvasRenderingContext2D.drawImage()
image
, . Image,
<img>, ,
Image(), Canvas.
x, y
.
width, height
, .
.
sourceX, sourceY
.
.
destX, destY
,
.
destWidth, destHeight
, .
.
,
.
,
.
:
.
, , Image,
Canvas. Image <img>
, Image().
Image
741
CanvasRenderingContext2D.fill()
CanvasRenderingContext2D.fill()
void fill()
fill() , ,
fillStyle. .
, , ,
closePath(). ( : ,
.)
, , ,
Canvas nonzero winding rule.
,
.
. fill()
stroke(), .
CanvasRenderingContext2D.fillRect()
CanvasRenderingContext2D.fillRect()
x, y
.
width, height
.
fillRect() ,
, fillStyle.
, fillRect() ,
beginPath().
.
.
CanvasRenderingContext2D.fill(),
text2D.strokeRect()
CanvasRenderingContext2D.rect(), CanvasRenderingCon
742
CanvasRenderingContext2D.globalCompositeOperation
CanvasRenderingContext2D.globalCompositeOperation
String globalCompositeOperation
,
.
. source ,
, destination ,
. "sourceover".
"copy"
"darker"
,
"destinationatop" ,
.
"destinationin"
,
.
"destinationout" ,
.
"destinationover"
"lighter"
,
"sourceatop"
,
"sourcein"
,
.
"sourceout"
,
"sourceover"
.
"xor"
,
CanvasRenderingContext2D.lineCap
,
String lineCap
CanvasRenderingContext2D.lineJoin
743
lineCap , .
.
. "butt".
"butt"
. ,
.
, .
"round"
,
, ,
"square"
, .
"butt",
CanvasRenderingContext2D.lineJoin
CanvasRenderingContext2D.lineJoin
,
String lineJoin
, / ,
lineJoin , .
.
, "miter", ,
, .
,
.
miterLimit. ,
.
"round" , , ,
, .
"bevel" , , ,
.
744
CanvasRenderingContext2D.lineTo()
CanvasRenderingContext2D.lineCap, CanvasRenderingContext2D.miterLimit
CanvasRenderingContext2D.lineTo()
x, y
lineTo() .
(x,y).
, (x,y).
.
CanvasRenderingContext2D.beginPath(), CanvasRenderingContext2D.moveTo()
CanvasRenderingContext2D.miterLimit
float miterLimit
line
Join "miter",
.
. miterLimit .
. 10, ,
10 .
, .
, lineJoin "round" "bevel".
Firefox 1.5 .
miterLimit,
("round").
CanvasRenderingContext2D.lineJoin
CanvasRenderingContext2D.moveTo()
CanvasRenderingContext2D.quadraticCurveTo()
745
x, y
.
moveTo() (x,y)
. ,
, .
CanvasRenderingContext2D.beginPath()
CanvasRenderingContext2D.quadraticCurveTo()
cpX, cpY
.
x, y
.
,
x y. , ,
(cpX, cpY).
(x,y).
Firefox 1.5 .
CanvasRenderingContext2D.bezierCurveTo()
CanvasRenderingContext2D.rect()
, ,
x, y
width, height .
.
,
. (0,0).
. CanvasRenderingContext2D.fillRect(), CanvasRenderingContext2D.strokeRect()
746
CanvasRenderingContext2D.restore()
CanvasRenderingContext2D.restore()
void restore()
CanvasRenderingContext2D,
. . save().
CanvasRenderingContext2D.save()
CanvasRenderingContext2D.rotate()
angle
.
, .
<canvas> , ,
, .
<canvas>. : .
,
Math.PI 180.
CanvasRenderingContext2D.scale(), CanvasRenderingContext2D.translate()
CanvasRenderingContext2D.save()
void save()
save()
.
restore().
CanvasRenderingContext2D.scale()
747
CanvasRenderingCon
text2D ( canvas),
, rotate(), scale()
translate(). , ,
clip(). ,
.
CanvasRenderingContext2D.restore()
CanvasRenderingContext2D.scale()
sx, sy
scale()
.
. , 2,0 0,5,
, scale().
sx
Y, sy
X.
.
CanvasRenderingContext2D.rotate(), CanvasRenderingContext2D.translate()
CanvasRenderingContext2D.stroke()
void stroke()
stroke() , .
, ,
strokeStyle, lineWidth, lineCap,
lineJoin miterLimit.
stroke () .
. stroke(), fill()
.
748
CanvasRenderingContext2D.strokeRect()
.
CanvasRenderingContext2D.fill(), CanvasRenderingContext2D.lineCap, CanvasRenderingCon
text2D.lineJoin, CanvasRenderingContext2D.strokeRect()
CanvasRenderingContext2D.strokeRect()
x, y
.
width, height
.
( )
.
strokeStyle lineWidth.
lineJoin.
strokeRect() ,
beginPath().
.
.
CanvasRenderingContext2D.fillRect(), CanvasRenderingContext2D.lineJoin, CanvasRender
ingContext2D.rect(), CanvasRenderingContext2D.stroke()
CanvasRenderingContext2D.translate()
dx, dy
X Y.
translate()
. dx dy
, .
CanvasRenderingContext2D.rotate(), CanvasRenderingContext2D.scale()
749
CDATASection
CDATASection
CDATA XML#
CDATA XML.
, HTML,
, .
CDATASection Text;
. CDATA
nodeValue, Node, data,
CharacterData. , CDATASection
, Text, , Node.normalize()
CDATA. CDATASection Document.createCDATASection().
CharacterData, Text
CharacterData
Text Comment
Comment, Text
String data
, .
readonly unsigned long length
, .
appendData()
.
deleteData()
,
.
insertData()
, .
replaceData()
,
.
substringData()
, .
750
CharacterData.appendData()
, , , Character
Data , Text Comment .
Comment, Text
CharacterData.appendData()
Text Comment
arg
, Text Comment.
arg data .
CharacterData.deleteData()
Text Comment
DOMException
code:
INDEX_SIZE_ERR
Text Comment.
NO_MODIFICATION_ALLOWED_ERR
.
751
CharacterData.insertData()
Text Comment,
. ,
Text Comment, ,
.
CharacterData.insertData()
Text Comment
Text Comment, .
arg
.
DOMException
code :
INDEX_SIZE_ERR
Text Com
ment.
NO_MODIFICATION_ALLOWED_ERR
.
CharacterData.replaceData()
Text Comment
Text Comment, .
752
CharacterData.substringData()
.
arg
, , .
DOMException
code :
INDEX_SIZE_ERR
, Text
Comment, .
NO_MODIFICATION_ALLOWED_ERR
.
, ,
arg. Text
Comment, , .
CharacterData.substringData()
Text Comment
.
, Text Comment,
.
DOMException code:
INDEX_SIZE_ERR
, Text
Comment, .
DOMSTRING_SIZE_ERR
,
JavaScript .
753
Checkbox
, ,
, Text Comment. ,
,
JavaScript .
JavaScript
data Text Comment,
. .
Checkbox
. Input
Comment
HTML# XML#
NodeCharacterDataComment
CharacterData
CSS2Properties
CSS#
String cssText
.
, CSS,
, .
DOMEx
ception SYNTAX_ERR code.
cssText, CSS2Properties ,
DOMException NO_MODIFICATION_AL
LOWED_ERR code.
cssText CSS2Properties
CSS, CSS2.
CSS ,
, JavaScript. ,
, "fontfamily", Java
Script , , ,
(: fontFamily). , "float"
float, cssFloat.
754
CSS2Properties
CSS2Properties, ,
CSS2, . :
CSS,
.
CSS,
. CSS
CSS, OReilly Cascading Style Sheets: The De
finitive Guide1 (Eric A. Meyer).
.
, cssText.
azimuth
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
border
borderBottom
borderBottomColor
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopStyle
borderTopWidth
borderWidth
bottom
captionSide
clear
clip
color
content
counterIncrement
counterReset
cssFloat
cue
cueAfter
cueBefore
cursor
direction
display
elevation
emptyCells
font
fontFamily
fontSize
fontSizeAdjust
fontStretch
fontStyle
fontVariant
fontWeight
height
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
markerOffset
marks
maxHeight
maxWidth
minHeight
minWidth
orphans
outline
outlineColor
outlineStyle
outlineWidth
overflow
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
page
pageBreakAfter
pageBreakBefore
pageBreakInside
pause
pauseAfter
pauseBefore
pitch
pitchRange
playDuring
position
quotes
richness
right
size
speak
speakHeader
speakNumeral
speakPunctuation
speechRate
stress
tableLayout
textAlign
textDecoration
CSS . , 3 .
. . .: , 2008.
755
CSSRule
textIndent
textShadow
textTransform
top
unicodeBidi
verticalAlign
visibility
voiceFamily
volume
whiteSpace
widows
width
wordSpacing
zIndex
CSS2Properties CSS .
CSS,
CSS2. style HTMLElement CSS2Pro
perties, /, style CSSRule.
Window.getComputedStyle() CSS2Properties,
.
CSSRule
CSS
ObjectCSSRule
String selectorText
, ,
.
DOMException NO_MODIFICATION_ALLOWED_ERR code,
, SYNTAX_ERR,
CSS.
readonly CSS2Properties style
, , selector
Text. : style
, CSS2Properties, ,
, .
CSSRule CSS:
,
. selectorText
, style CSS2Properties,
, .
DOM Level 2 CSS
CSSRule ,
CSSStyleSheet. , ,
DOM CSSStyleRule.
,
, . IE
DOM Level 2 ( ,
IE 7), CSSRule, .
CSS2Properties, CSSStyleSheet
756
CSSStyleSheet
CSS
CSSStyleSheet
DOM Level 2 CSS, IE 4
ObjectCSSStyleSheet
addRule()
IE CSS .
deleteRule()
DOM, .
insertRule()
DOM, .
removeRule()
IE .
757
CSSStyleSheet.addRule()
CSS.
, , ,
. IE ,
DOM. IE cssRules[] rules[],
insertRule() deleteRule() addRule() removeRule().
CSSStyleSheet, ,
styleSheets[] Document. , DOM (
),
<style> <link> ProcessingInsrtuction,
, CSSStyleSheet
sheet.
CSSStyleSheet.addRule()
IE 4
IE
void addRule(String ,
String ,
integer )
CSS .
, ,
. ,
.
.
rules, .
, .
( ) rules CSS
.
insertRule(), IE. : addRule() insertRule()
.
CSSStyleSheet.deleteRule()
758
CSSStyleSheet.insertRule()
cssRules.
DOMException INDEX_SIZE_ERR,
cssRules.length.
, DOMException NO_MODIFICATION_ALLOWED_ERR.
, , cssRules.
DOM; CSSStyleSheet.removeRule(),
IE, .
CSSStyleSheet.insertRule()
,
, .
, .
cssRules, .
.
DOMException
code :
HIERARCHY_REQUEST_ERR
CSS .
INDEX_SIZE_ERR
, cssRules.length.
NO_MODIFICATION_ALLOWED_ERR
.
SYNTAX_ERR
.
CSSStyleSheet.removeRule()
759
( ) CSS ,
cssRules . DOM;
CSSStyleSheet.addRule(), IE,
.
CSSStyleSheet.removeRule()
IE 4
IE
void removeRule(integer )
rules[].
, .
CSS, rules[].
deleteRule(),
IE.
Document
HTML# XML#
NodeDocument
HTMLDocument
760
Document
addEventListener()
. DOM,
IE.
attachEvent()
. , IE add
EventListener().
createAttribute()
Attr .
createAttributeNS()
Attr .
createCDATASection()
CDATASection, .
createComment()
Comment, .
createDocumentFragment()
DocumentFragment.
createElement()
Element .
createElementNS()
Element .
createEvent()
Event .
createExpression()
XPathExpression,
XPath. , IE, Node.se
lectNodes().
createProcessingInstruction()
ProcessingInstruction .
createRange()
Range.
DocumentRange; Document ,
Range.
createTextNode()
Text, .
detachEvent()
.
removeEventListener(), IE.
dispatchEvent()
.
Document
761
evaluate()
XPath . ,
IE, Node.selectNodes().
getElementById()
,
id, null, .
getElementsByTagName()
( NodeList) Element ,
. Element
, .
getElementsByTagNameNS()
,
.
importNode()
,
.
loadXML()
XML
.
removeEventListener()
. DOM ,
IE.
Document . Document
, Element
.
documentElement. doctype implementation
DocumentType ( ) DOMImplementation .
, Document,
, ,
. getElementById() getEle
mentsByTagName(),
.
, addEventHandler(). ,
, Ele
ment Element.
Document document
Window. , Document contentDocument
Frame IFrame, ownerDocument Node,
.
XML ( XHTML)
Document createDocment() DOMImplementation:
document.implementation.createDocument(namespaceURL, rootTagName, null);
762
Document.addEventListener()
IE :
new ActiveXObject("MSXML2.DOMDocument");
,
Document, 21.1. ,
XML Document. (.
responseXML XMLHttpRequest.)
XML Document DOMParser.parseFromString()
IE Document.loadXML(). ( 21.4
,
XML.)
, HTML,
HTMLDocument.
.
DOMImplementation, DOMParser, HTMLDocument, Window, XMLHttpRequest; 15
Document.addEventListener()
. Element.addEventListener()
Document.attachEvent()
. Element.attachEvent()
Document.createAttribute()
Attr
Attr createAttribute(String )
throws DOMException;
.
Attr nodeName, .
DOMException , INVALID_CHARACTER_ERR,
.
763
Document.createAttributeNS()
Document.createAttributeNS()
Attr
URI
Attr null
.
, ,
.
Attr .
DOMException
:
INVALID_CHARACTER_ERR
.
NAMESPACE_ERR
URI.
NOT_SUPPORTED_ERR
XML, ,
.
createAttributeNS() createAttribute(), ,
Attr , .
XML,
.
Document.createCDATASection()
CDATASection
CDATASection createCDATASection(String )
throws DOMException;
CDATA.
764
Document.createComment()
CDATASection, .
HTML DOMException ,
NOT_SUPPORTED_ERR, . . HTML CDATASection
.
Document.createComment()
Comment
Comment createComment(String );
Comment.
Comment, .
Document.createDocumentFragment()
DocumentFragment
DocumentFragment createDocumentFragment();
DocumentFragment, .
Document.createElement()
Element
Element createElement(String )
throws DOMException;
. HTML ,
XML .
Element .
DOMException INVALID_CHARACTER_ERR,
.
Document.createElementNS()
Document.createElementNS()
765
DOM Level 2 Core
Element
URI
null
.
Element.
, .
Element .
DOMException
code :
INVALID_CHARACTER_ERR
.
NAMESPACE_ERR
URI.
NOT_SUPPORTED_ERR
XML, ,
.
createElementNS() createElement(), ,
Element ,
. XML,
.
Document.createEvent()
Event
Event createEvent(String )
throws DOMException;
, Event.
.
766
Document.createExpression()
Event .
DOMException NOT_SUPPORTED_ERR,
.
, , .
:
, DOM, .
, .
eventType
HTMLEvents
Event
initEvent()
MouseEvents
MouseEvent
initMouseEvent()
UIEvents
UIEvent
initUIEvent()
Event , ,
.
.
Document, DOM
DocumentEvent. Events, Document
DocumentEvent .
Document.createExpression()
XPath
XPathExpression createExpression(String ,
Function URL)
throws XPathException
, XPath.
URL
,
URL null,
.
XPathExpression.
767
Document.createProcessingInstruction()
,
,
URL.
, XPath,
XPathExpression.
function(prefix),
URL
.
Internet Explorer. , IE,
Node.selectNodes().
Document.createProcessingInstruction()
ProcessingInstruction
ProcessingInstruction createProcessingInstruction(String ,
String )
throws DOMException;
ProcessingInstruction.
DOMException
code :
INVALID_CHARACTER_ERR
.
NOT_SUPPORTED_ERR
HTML, .
Document.createRange()
Range
Range createRange();
Range,
.
768
Document.createTextNode()
Range,
DocumentFragment,
.
: Document,
DocumentRange. Range, Docu
ment DocumentRange .
Document.createTextNode()
Text
Text createTextNode(String );
Text.
Text, .
Document.detachEvent()
. Element.detachEvent()
Document.dispatchEvent()
. Element.dispatchEvent()
Document.evaluate()
XPath
XPathResult evaluate(String ,
Node ,
Function URL,
short ,
XPathResult )
throws DOMException, XPathException
, XPath.
, .
Document.getElementById()
769
URL
,
URL null,
.
, .
,
XPathResult.
XPathResult null, .
XPathResult,
.
,
,
, ,
URL,
.
XPath
XPathResult,
. ,
Document.createEx
pression(), evaluate() XPathExpression.
Internet Explorer. , IE,
Node.selectNodes() Node.selectSingle
Node().
.
Document.createExpression(), Node.selectNodes(), Node.selectSingleNode(), XPathExpres
sion, XPathResult
Document.getElementById()
(ID)
Id
id .
Element, id,
null, .
770
Document.getElementsByTagName()
.
Document.getElementsByTagName(), Element.getElementsByTagName(),
mentsByName()
Document.getElementsByTagName()
HTMLDocument.getEle
Element
Node[] getElementsByTagName(String );
Element, , *
Element . HTML
( 6 IE
*).
( NodeList) Element
. Element
, .
NodeList ( ,
), Element ,
, ,
. NodeList , . .
,
.
771
Document.getElementsByTagNameNS()
HTML ,
. XML ,
,
.
: Element ,
. , HTMLDocument
getElementsByName(),
name, .
<h1> :
var headings = document.getElementsByTagName("h1");
for(var i = 0; i < headings.length; i++) { //
var h = headings[i];
// <h1> h
}
.
Document.getElementById(), Element.getElementsByTagName(), HTMLDocument.getElementsBy
Name()
Document.getElementsByTagNameNS()
Element
URI
* .
*
.
( NodeList) Element
, .
, getElementsByTagName(), ,
, .
XML, .
772
Document.importNode()
Document.importNode()
Node importNode(Node ,
boolean )
throws DOMException;
, .
true, .
(, , ),
ownerDocument .
DOMException NOT_SUPPORTED_ERR,
Document DocumentType, . .
.
, ,
, . true,
.
. ownerDocument
, parentNode null,
. ,
, .
Element, ,
. Attr, specified
true.
Node.cloneNode()
Document.loadXML()
Internet Explorer
XML
void loadXML(String )
XML, .
IE ,
XML, DOM Document.
, , .
Document.removeEventListener()
773
Document, HTML.
loadXML() Document,
XML:
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.loadXML(markup);
, IE,
DOMParser.parseFromString().
DOMParser.parseFromString()
Document.removeEventListener()
. Element.removeEventListener()
DocumentFragment
DocumentFragment () .
, ,
. DocumentFragment
, parentNode null.
DocumentFragment :
DocumentFragment , Document
Fragment, . DocumentFragment
,
. DocumentFragment
, , Range.
DocumentFragment Document.create
DocumentFragment(), DocumentFragment,
, Range.extractContents() Range.cloneCon
tents().
Range
DocumentType
DTD XML#
NodeDocumentType
774
DOMException
DTD XML.
, HTML,
.
DTD , DocumentType
. XML DTD, Docu
mentType doctype
Document.
W3C DOM API
XML, DTD, .
DTD
JavaScript .
JavaScript
<!DOCTYPE>, DTD,
.
DocumentType .
.
Document, DOMImplementation.createDocument(), DOMImplementation.createDocumentType()
DOMException
DOM
code
DOMException. :
DOMException, .
unsigned short INDEX_SIZE_ERR = 1
.
unsigned short DOMSTRING_SIZE_ERR = 2
JavaScript.
unsigned short HIERARCHY_REQUEST_ERR = 3
.
unsigned short WRONG_DOCUMENT_ERR = 4
, ,
.
DOMException
775
776
DOMImplementation
, . ,
Node ( )
. , ,
XML, HTML, . .
DOMException
Node, NO_MODIFICATION_ALLOWED_ERR
.
DOM DOM, ,
DOMException DOMSTRING_SIZE_ERR, ,
JavaScript. ,
,
.
: DOMException
DOM. , DOM Range,
RangeException.
RangeException
DOMImplementation
,
createDocument()
Document ( documentElement
Document) .
createDocumentType()
DocumentType.
hasFeature()
,
.
DOMImplementation ,
, Document,
DOM. DOMImplemen
tation implementation Document.
DOMImplementation.createDocument()
DOMImplementation.createDocumentType()
777
URI
null .
.
URI null,
.
DocumentType null,
.
Document documentElement,
Element .
DOMException
code :
INVALID_CHARACTER_ERR
.
NAMESPACE_ERR
URI.
NOT_SUPPORTED_ERR
XML .
WRONG_DOCUMENT_ERR
DOMImplementation.
XML docu
mentElement . null,
ownerDocument DocumentType
.
XML
, HTML.
DOMImplementation.createDocumentType()
DOMImplementation.createDocumentType()
DocumentType
DocumentType createDocumentType(String ,
String publicId,
String systemId)
throws DOMException;
778
DOMImplementation.hasFeature()
. XML,
, , ,
.
publicId
null.
systemId
null.
DTD.
DocumentType ownerDocument, null.
DOMException
code :
INVALID_CHARACTER_ERR
.
NAMESPACE_ERR
.
NOT_SUPPORTED_ERR
XML .
DocumentType
. DOM Level 2
, DocumentType
Entity Notation. XML.
DOMImplementation.hasFeature()
boolean hasFeature(String ,
String );
(feature), .
DOM Level 2 .
.
null "",
. DOM Level 2
1.0 2.0.
DOMImplementation.hasFeature()
779
true,
, false .
true,
.
W3C DOM ,
, .
, DOM .
DOM
. , Internet Explorer 5 5.5
DOM Level 1, IE 6 .
, ,
.
Core
HTML
HTMLElement, HTMLDocument ,
HTML
XML
StyleSheets
CSS
, CSS.
CSS2
CSS2Properties
Events
UIEvents
MouseEvents
HTMLEvents
HTML
MutationEvents
Range
Traversal
Views
:
// , DOM Level 2 Range API
if (document.implementation &&
document.implementation.hasFeature &&
document.implementation.hasFeature("Range", "2.0")) {
// , ...
}
780
DOMParser
else {
// , , Range
}
Node.isSupported()
DOMParser
XML# Document
ObjectDOMParser
new DOMParser()
parseFromString()
XML Document.
DOMParser XML
Document XML. DOMParser,
, parse
FromString():
var doc = (new DOMParser( )).parseFromString();
Document.loadXML(), XMLHttpRequest; 21
DOMParser.parseFromString()
XML#
Document parseFromString(String ,
String )
XML.
. "text/xml", "application/
xml" "application/xhtml+xml". : text/html
.
Document, .
, IE, Document.loadXML().
781
Element
Element
HTML# XML#
ObjectElement
HTMLElement
addEventListener()
. DOM ,
IE.
attachEvent()
. , IE add
EventListener().
detachEvent()
.
removeEventListener(), IE.
dispatchEvent()
.
getAttribute()
.
getAttributeNS()
, URI
. XML
, .
getAttributeNode()
Attr.
getAttributeNodeNS()
Attr , URI
. XML,
.
getElementsByTagName()
( NodeList) Element,
, ,
.
782
Element
getElementsByTagNameNS()
, getElementsByTagName(), ,
URI .
XML, .
hasAttribute()
true, , false
. : true,
DTD
.
hasAttributeNS()
, hasAttribute(), ,
URI .
XML, .
removeAttribute()
. ,
,
. DTD ,
, .
removeAttributeNode()
Attr .
, ,
. DTD ,
, Attr
, .
removeAttributeNS()
, removeAttribute(), ,
URI .
XML,
.
removeEventListener()
. DOM ,
IE.
setAttribute()
, .
,
.
setAttributeNode()
Attr .
, .
setAttributeNodeNS()
, setAttributeNode(), ,
Document.createAttributeNS().
XML, .
Element.addEventListener()
783
setAttributeNS()
, setAttribute(), ,
URI .
XML,
.
HTMLElement, Node; 15 17
Element.addEventListener()
void addEventListener(String ,
Function ,
boolean );
784
Element.attachEvent()
, .
, "load", "click" "mousedown".
,
.
Event, , ,
.
true,
. false,
, ,
.
.
true,
. false,
.
addEventListener()
.
, DOM
.
, .
,
.
Node.cloneNode() Document.import
Node(), , ,
.
Document
Window.
Event; 17
Element.attachEvent()
void attachEvent(String ,
Function );
IE 4
Element.detachEvent()
785
, .
on, : "onload", "onclick"
"onmousedown".
,
.
, Event event
Window.
IE.
, addEventListener() (
IE), :
IE , at
tachEvent() detachEvent() :
.
, IE,
on. , attach
Event() "onclick",
addEventListener() "click".
, attachEvent(),
Event .
event Window.
, attachEvent(),
, , .
, attach
Event(), this Window, ,
.
attachEvent()
. , ,
.
Document Window.
Element.addEventListener(), Event; 17
Element.detachEvent()
IE 4
void detachEvent(String ,
Function )
, .
on, "onload", "onclick" "onmousedown".
786
Element.dispatchEvent()
, .
,
attachEvent(). removeEventListener(),
IE. ,
detachEvent() , attachEvent().
Document Window.
Element.dispatchEvent()
boolean dispatchEvent(Event )
throws EventException;
Event, .
false, preventDefault()
, true .
, ,
, type null .
, Document.cre
ateEvent() ,
Event . ,
, ,
, , bubbles
true,
, .
Element.getAttribute()
String getAttribute(String );
, .
787
Element.getAttributeNode()
.
, .
null.
getAttribute() .
, , HTML, Java
Script, HTML,
.
XML
, . XML,
, getAttributeNS()
getAttributeNodeNS().
HTML <img>:
//
var images = document.body.getElementsByTagName("img");
// src
var src0 = images[0].getAttribute("src");
// src
var src1 = images[1].src;
Element.getAttributeNode()
Attr
Attr getAttributeNode(String );
Attr, , null,
.
getAttributeNode() Attr,
. : Attr
attributes, Node.
Element.getAttribute(), Element.getAttributeNodeNS()
788
Element.getAttributeNodeNS()
Element.getAttributeNodeNS()
Attr
URI
URI, , null,
.
, .
Attr, , null,
.
, getAttributeNode(), ,
URI ,
.
XML, .
Element.getAttributeNode(), Element.getAttributeNS()
Element.getAttributeNS()
URI
URI, , null,
.
, .
.
, ,
null.
, getAttribute(), ,
URI ,
Element.getElementsByTagName()
789
.
XML, .
Element.getAttribute(), Element.getAttributeNodeNS()
Element.getElementsByTagName()
Element[] getElementsByTagName(String );
*, ,
.
( NodeList) Element,
.
(
NodeList) Element,
.
, .
: Document getElementsByTagName(),
, ,
. HTMLDocument.getElementsByName(),
name, .
<div> :
var divisions = document.body.getElementsByTagName("div");
<p> <div>:
var paragraphs = divisions[0].getElementsByTagname("p");
.
Document.getElementById(), Document.getElementsByTagName(), HTMLDocument.getElementsBy
Name()
Element.getElementsByTagNameNS()
#
790
Element.hasAttribute()
URI
URI, .
, .
( NodeList) Element,
.
, getElementsByTagName(),
URI ,
.
XML, .
Document.getElementsByTagNameNS(), Element.getElementsByTagName()
Element.hasAttribute()
boolean hasAttribute(String );
true, ,
, false .
, ,
. : hasAttribute()
true, ,
, .
Element.getAttribute(), Element.setAttribute()
Element.hasAttributeNS()
,
791
Element.removeAttribute()
URI
null
.
.
true, ,
, false.
, hasAttribute(), ,
.
XML, .
.
Element.getAttributeNS(), Element.hasAttribute(), Element.setAttributeNS()
Element.removeAttribute()
void removeAttribute(String );
DOMException NO_MODIFICATION_AL
LOWED_ERR,
.
removeAttribute() .
,
getAttribute() .
, ,
, .
Element.removeAttributeNode()
Attr
Attr removeAttributeNode(Attr )
throws DOMException;
792
Element.removeAttributeNS()
Attr, .
Attr.
DOMException
code:
NO_MODIFICATION_ALLOWED_ERR
.
NOT_FOUND_ERR
.
( ) Attr .
DTD ,
Attr, .
removeAttribute().
Attr, Element.removeAttribute()
Element.removeAttributeNS()
URI
null
.
DOMException NO_MODIFICATION_AL
LOWED_ERR,
.
removeAttributeNS() , removeAttribute(),
, ,
. XML,
.
793
Element.removeEventListener()
.
Element.getAttributeNS(), Element.removeAttribute(), Element.setAttributeNS()
Element.removeEventListener()
void removeEventListener(String ,
Function ,
Boolean );
, .
, .
true, , false,
.
.
, addEventListener().
, , ,
.
,
.
,
.
Document
Window.
Element.setAttribute()
void setAttribute(String ,
String )
throws DOMException;
DOMException
code:
794
Element.setAttributeNode()
INVALID_CHARACTER_ERR
, HTML XML.
NO_MODIFICATION_ALLOWED_ERR
.
.
, . :
HTMLElement HTML JavaScript,
HTML.
.
// TARGET
var links = document.body.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
links[i].setAttribute("target", "newwindow");
// : links[i].target = "newwindow";
}
.
Element.getAttribute(), Element.removeAttribute(), Element.setAttributeNode()
Element.setAttributeNode()
Attr
Attr setAttributeNode(Attr )
throws DOMException;
Attr, ,
.
Attr, , null,
.
DOMException
code:
INUSE_ATTRIBUTE_ERR
Element.
NO_MODIFICATION_ALLOWED_ERR
Element .
795
Element.setAttributeNodeNS()
WRONG_DOCUMENT_ERR
ownerDocument ,
.
Attr Element.
, ,
Attr .
, .
setAttributeNode() setAttribute().
Element.setAttributeNodeNS()
Attr
Attr setAttributeNodeNS(Attr )
throws DOMException;
Attr, ,
.
Attr, , null,
.
, setAttributeNode().
DOMException NOT_SUPPORTED_ERR,
, ,
XML .
, setAttributeNode(), ,
Attr, ,
.
XML,
. (. .
NOT_SUPPORTED_ERR) , XML.
.
Attr, Document.createAttributeNS(), Element.setAttributeNS(), Element.setAttributeNode()
796
Element.setAttributeNS()
Element.setAttributeNS()
URI
URI, ,
, null .
, ,
.
DOMException
code:
INVALID_CHARACTER_ERR
, HTML
XML.
NAMESPACE_ERR
URI
.
NO_MODIFICATION_ALLOWED_ERR
.
NOT_SUPPORTED_ERR
DOM XML.
setAttribute(), ,
URI ,
,
.
XML,
. (. .
NOT_SUPPORTED_ERR) , XML.
Element.setAttribute(), Element.setAttributeNode()
797
Event
Event
ObjectEvent
UIEvent
DOM Level 2 Events.
KeyEvent, MouseEvent UIEvent:
readonly boolean bubbles
true, (
stopPropagation()), false .
readonly boolean cancelable
true, ,
, preventDefault(), false
.
readonly Object currentTarget
Element, Document Window, .
target.
readonly unsigned short eventPhase
.
, ,
:
Event.CAPTURING_PHASE
Event.AT_TARGET
Event.BUBBLING_PHASE
IE
Internet Explorer ( , IE 7)
DOM, Event IE .
798
Event
IE
,
:
boolean altKey
, Alt .
integer button
button ,
. :
, 1, , ,
2, ,
4, ( ).
boolean cancelBubble
,
true.
integer clientX, clientY
, .
boolean ctrlKey
, Ctrl .
Element fromElement
mouseover mouseout fromElement ,
.
integer keyCode
Unicode ,
. keydown keyup
.
.
integer offsetX, offsetY
, ,
(. srcElement).
boolean returnValue
, ,
.
false, ,
, .
integer screenX, screenY
, .
boolean shiftKey
, Shift .
Object srcElement
Window, Document Element, .
Element toElement
mouseover mouseout ,
.
799
Event.initEvent()
String type
. on.
, onclick(), type
Event "click".
integer x, y
X Y
, CSS.
DOM Lebel 2 Events.
IE Event :
initEvent()
Event.
preventDefault()
, ,
, .
, .
stopPropagation()
,
.
,
.
Event , ,
, . Event
. DOM Level 2 Events
, ,
Internet Explorer, .
Event,
Event IE.
17. ,
Event ,
IE event Window.
Event
,
. IE Event,
.
Event.initEvent()
800
Event.preventDefault()
eventTypeArg
. ,
"load" "submit", , .
, DOM, .
canBubbleArg
.
cancelableArg
preventDefault().
.
Document.createEvent(), MouseEvent.initMouseEvent(), UIEvent.initUIEvent()
Event.preventDefault()
void preventDefault();
,
( ). , type "submit",
, ,
, . :
cancelable Event false, ,
, , .
.
Event.stopPropagation()
void stopPropagation();
.
. :
,
.
801
ExternalInterface
ExternalInterface
ActionScript Flash 8
Flash
available
, Flash JavaScript.
false,
.
addCallback()
ActionScript , Java
Script.
call()
JavaScript ActionScript.
ExternalInterface ActionSript,
Flash 8 .
ActionScript Flash.
JavaScript ActionCript
Flash.
FlashPlayer; 23
ExternalInterface.addCallback()
ActionScript Flash 8
ActionScript JavaScript
boolean ExternalInterface.addCallback(String ,
Object ,
Function )
, .
ActionScript .
ActionScript, , null.
this.
ActionScript, JavaScript
.
true false .
802
ExternalInterface.call()
ActionScript Flash,
JavaScript ActionScript
. addCallback() JavaScript
, ActionScript
ActionScript .
JavaScript ,
Java
Script.
: , , ,
, .
JavaScript ActionScript , Win
dow Document. JavaScript
Flash ActionScript, MovieClip.
FlashPlayer; 23
ExternalInterface.call()
ActionScript Flash 8
JavaScript ActionScript
Object ExternalInterface.call(String ,
Object ...)
JavaScript.
...
, JavaScript
.
JavaScript, ActionScript
.
ActionScript Flash
JavaScript, , Flash
.
ActionScript JavaScript
ExternalInterface.addCallback().
FileUpload
. Input
803
FlashPlayer
FlashPlayer
Flash 2.0
Flash#
GetVariable()
, Flash.
GotoFrame()
.
IsPlaying()
, .
LoadMovie()
Flash
.
Pan()
.
PercentLoaded()
, .
Play()
.
Rewind()
.
SetVariable()
, .
SetZoomRect()
Flash.
StopPlay()
.
TotalFrames()
.
Zoom()
.
FlashPlayer Flash
Flash, .
FlashPlayer , , Document.getEle
mentById(), <embed> <object>, Flash
.
FlashPlayer ,
JavaScript ,
. : FlashPlayer
, ,
JavaScript.
23.
804
FlashPlayer.GetVariable()
FlashPlayer.GetVariable()
Flash 4
, Flash#
String GetVariable(String )
, Flash.
null,
.
FlashPlayer.GotoFrame()
Flash 2
void GotoFrame(integer )
, .
, .
, PercentLoaded() ,
.
FlashPlayer.IsPlaying()
Flash 2
boolean IsPlaying()
true, , false .
FlashPlayer.LoadMovie()
void LoadMovie(integer ,
String url)
Flash 3
805
FlashPlayer.Pan()
, , ,
.
url
URL .
URL,
url, .
FlashPlayer.Pan()
Flash 2
dx, dy
.
, dx dy.
0,
. 1,
.
Flash ,
Flash. , ,
SetZoomRect() Zoom():
,
.
, Pan()
,
. .
FlashPlayer.SetZoomRect(), FlashPlayer.Zoom()
FlashPlayer.PercentLoaded()
Flash 2
integer PercentLoaded()
0 100,
, .
806
FlashPlayer.Play()
FlashPlayer.Play()
Flash 2
void Play()
FlashPlayer.Rewind()
Flash 2
void Rewind()
FlashPlayer.SetVariable()
Flash 4
, Flash#
, .
. .
, .
FlashPlayer.SetZoomRect()
Flash 2
left, top
.
right, bottom
.
, . .
Flash, .
807
FlashPlayer.StopPlay()
Flash , . 20
, a 1440 .
FlashPlayer.Pan(), FlashPlayer.Zoom()
FlashPlayer.StopPlay()
Flash 2
void StopPlay()
FlashPlayer.TotalFrames()
Flash 2
integer TotalFrames()
FlashPlayer.Zoom()
Flash 2
void Zoom(integer )
0
.
.
1 99 ,
. 100 (
),
. 0 :
0,
.
Form
<form> HTML#
808
Form
action
URL
String enctype
enctype
String method
method
HTTP,
String name
name
String target
target
reset()
,
.
submit()
onreset
.
onsubmit
.
.
HTML
Form HTML <form>.
, <input>, <select>, <textarea> :
<form
[ name="_" ]
// , JavaScript
[ target="_" ]
//
[ action="url" ]
// URL,
[ method=("get"|"post") ] //
[ enctype="" ] //
[ onreset="" ] // ,
[ onsubmit="" ] // ,
>
//
</form>
809
Form.elements[]
Document.forms[].
_
Document, _ , name <form>.
(, , . .)
Form.elements[]. , ,
Form. , Input phone
questionnaire JavaScript:
document.questionnaire.phone
Form.elements[]
elements[] HTMLCollection,
( Input, Select Textarea).
, HTML.
type,
.
elements[] name=""
HTML <input>, form,
. , :
form.
Form.onreset
DOM Level 0
Function onreset
onreset Form , ,
Reset
Form.reset(). onreset false,
.
Element.addEventListener().
810
Form.onsubmit
Form.onsubmit
DOM Level 0
Function onsubmit
onsubmit Form , ,
Submit
. :
Form.submit().
onsubmit false,
.
, . onsubmit
,
.
Element.addEventListener().
Form.reset()
void reset();
reset() ,
, , Reset,
, onreset() .
Form.onreset, Form.submit()
Form.submit()
void submit();
submit() .
, Submit,
, onsubmit .
Form.onsubmit, Form.reset()
811
Frame
Frame
<frame> HTML#
NodeElementHTMLElementFrame
, HTML Frame
Window. Frame,
HTMLElement :
Document contentDocument
, .
String src
URL, .
.
src <frame> Location,
Window.location.
Frame ,
HTML:
String frameBorder
frameborder
"0"
String longDesc
longdesc
URL
marginwidth
String name
name
DOM
Level 0 target
boolean noResize
noresize
true,
String scrolling
scrolling
JavaScript
Window, Frame.
DOM Level 0 <frame>
Window,
frames[] :
// Window
var win1 = top.frames[0];
// frames[]
var win2 = top.frames['f1']; // frames[]
var win3 = top.f1;
//
, Window
, ,
. Window, document
location URL .
DOM Level 2 <frame> id
name , :
812
Hidden
// Frame
var frame1 = top.document.getElementById('f1');
// id
var frame2 = top.document.getElementsByTagName('frame')[1]; //
DOM,
, Window, Frame,
.
contentDocument, URL
src. Frame
Window, f.contentDocument.defaultView.
<iframe> <frame>.
IFrame.
, , ,
(. 13.8.2).
,
, . ,
, Window Frame.
IFrame, Window; 14
Hidden
. Input
History
JavaScript 1.0
ObjectHistory
window.history
history
length
URL ()
. ,
.
back()
URL.
forward()
URL.
go()
URL.
History
. History
URL. ,
, History back(), forward()
go().
813
History.back()
, :
history.back();
, :
history.go(2);
History.back()
JavaScript 1.0
URL#
history.back()
back() ,
History, URL ( ),
. ,
. :
history.go(1);
History.forward()
JavaScript 1.0
URL#
history.forward()
forward() ,
History, URL ( ),
. ,
. :
history.go(1);
:
, JavaScript
History.back() History.go(), forward() , . .
URL ,
.
History.go()
URL#
history.go(_)
history.go(_)
JavaScript 1.0
814
HTMLCollection
_
URL,
.
_
URL ( ), .
History.go()
URL, ,
History.
, . , history.go(1)
history.back() , .
history.go(3) URL,
history.forward().
History.go() ,
(. . ) URL,
.
. Mi
crosoft , _
URL, Netscape (
History Netscape) ,
URL.
HTMLCollection
HTML#,
item()
, .
, ( ).
namedItem()
, id
name, null, .
( ), .
HTMLCollection HTML ,
, id
name. JavaScript HTMLCollection
, HTMLCollection
JavaScript ,
item() namedItem().
815
HTMLCollection.item()
HTMLDocument HTMLCollection,
, , .
Form.elements Select.options HTMLCollection. ,
HTMLCollection HTML
.
HTMLCollection
JavaScript. , . .
,
HTMLCollection.
HTMLCollection NodeList,
, .
var
var
var
var
var
c = document.forms;
firstform = c[0];
lastform = c[c.length1];
address = c["address"];
address = c.address;
//
//
//
//
//
HTML
length
JavaScript
HTMLDocument, NodeList
HTMLCollection.item()
. HTMLCollection
, .
null,
length.
NodeList.item()
816
HTMLCollection.namedItem()
HTMLCollection.namedItem()
Node namedItem(String );
id name, null,
HTMLCollection .
HTMLCollection,
. id,
, . ,
, name .
, namedItem() null.
: id HTML,
HTML, , ,
, name.
JavaScript HTMLCollection
, .
HTMLDocument
HTML#
DOM Level 0
NodeDocumentHTMLDocument
HTMLDocument
817
HTMLElement body
, HTMLBodyElement,
<body> . ,
, <frameset>.
String cookie
cookie .
. HTMLDocument.cookie.
readonly String domain
, , null,
.
. .
HTMLDocument.domain.
readonly HTMLCollection forms
(HTMLCollection) Form .
readonly HTMLCollection images
(HTMLCollection) Image . :
DOM Level 0 , <object>,
.
readonly HTMLCollection lastModified
.
HTTP LastModified,
.
readonly HTMLCollection links
(HTMLCollection) Link .
readonly String referrer
URL, , null,
. HTTP
referer. :
r, JavaScript .
String title
<title> .
readonly String URL
URL . loca
tion.href Window, .
URL URL , lo
cation.href URL.
close()
, open(),
.
getElementsByName()
(NodeList) ,
name .
818
HTMLDocument.all[]
open()
,
. :
.
write()
HTML .
writeln()
HTML
.
Document
HTML .
HTMLCollection ( , ,
), , ,
, .
DOM Level 0. Docu
ment.getElementsByTagName(),
.
write(),
.
: DOM Level 1 HTMLDocument
getElementById(). DOM Level 2
Document HTMLDocument, .
. Document.getElementById().
HTMLDocument.all[]
IE4
HTML#
document.all[i]
document.all[]
document.all.tags()
all[] , .
HTML . all[] IE 4,
.
getElementById() getElementsByTagName() Document,
getElementsByName() HTMLDocument.
, all[] .
all[] ,
. ,
.
HTMLDocument.close()
819
all[] id name.
,
all[] .
all.tags() HTML
.
HTMLDocument.close()
DOM Level 0
void close();
, open(),
.
write() close(),
. close() write()
, . . open(),
.
HTMLDocument.open(), HTMLDocument.write()
HTMLDocument.cookie
DOM Level 0
cookie#
String cookie
cookie , , ,
cookie . Cookie ,
. Cookie
, ,
. , cookie,
,
. JavaScript
cookie
.
HTMLDocument.cookie , ,
. HTMLDocument.cookie ,
, ,
.
19.
820
HTMLDocument.domain
Cookies .
, .
: 20 cookies ,
cookie, , 4 .
19
HTMLDocument.domain
DOM Level 0
String domain
13.8.2
HTMLDocument.getElementsByName()
name
Element[] getElementsByName(String );
name.
821
HTMLDocument.open()
HTML Element,
name, , NodeList
( ), .
, NodeList length, 0.
Document.getElementById(),
Element id,
Document.getElementsByTagName(), NodeList
.
Document.getElementById(), Document.getElementsByTagName()
HTMLDocument.open()
DOM Level 0
void open();
HTML ,
write() writeln(). open()
write()
close() .
,
, . .
.
var w = window.open("");
var d = w.document;
d.open();
d.write("<h1>Hello world</h1>");
d.close();
//
//
//
//
//
HTMLDocument
HTML
HTMLDocument.close(), HTMLDocument.write()
HTMLDocument.write()
HTML#
void write(String );
DOM Level 0
822
HTMLDocument.writeln()
HTML.
.
DOM .
write() .
.
Document.write() . ,
,
<script>, . write()
HTML , ,
, , .
, Document.write()
, , ,
.
, write() .
, write() ()
, .
Document.write()
.
, Document.clo
se(). : open() ,
close() .
Document.write() ,
.
Document.close()
.
HTMLDocument.close(), HTMLDocument.open()
HTMLDocument.writeln()
DOM Level 0
HTML#
void writeln(String );
text
HTML, .
HTMLDocument.write(), ,
, ,
<pre>.
HTMLDocument.write()
823
HTMLElement
HTMLElement
HTML#
HTML ,
HTML. , HTML
. , HTML,
. HTMLElement
Node Element
, :
String className
class , CSS,
. :
class, . . JavaScript .
CSS2Properties currentStyle
, IE,
CSS, .
Window.getComputedStyle().
String dir
dir , .
String id
id.
id.
String innerHTML
, HTML,
,
.
HTML.
HTML .
(
HTMLDocument.write()).
IE 4. .
String lang
lang, .
int offsetHeight, offsetWidth
,
, . ,
.
int offsetLeft, offsetTop
X Y CSS
offsetParent. ,
.
Element offsetParent
, ,
offsetLeft offsetTop.
824
HTMLElement
offsetParent Document.
,
offsetParent
.
, ,
.
16. , .
int scrollHeight, scrollWidth
.
(, CSS overflow),
offsetHeight offsetWidth,
. ,
.
int scrollLeft, scrollTop
,
. ,
, , CSS overflow auto.
<body> <html> ( ),
. :
<iframe>. ,
.
CSS2Properties style
style, CSS .
: . .
CSS2Properties.
String title
title,
.
HTML
. ,
, ,
.
(. , Input Link):
onclick
, .
825
HTMLElement
ondblclick
, .
onkeydown
, .
onkeypress
, .
onkeyup
, .
onmousedown
, .
onmousemove
, .
onmouseout
,
.
onmouseover
, .
onmouseup
, .
HTML HTMLElement,
, , HTML
. ,
, HTMLElement:
<abbr>
<acronym>
<address>
<b>
<bdo>
<big>
<center>
<cite>
<code>
<dd>
<dfn>
<dt>
<em>
<i>
<kbd>
<noframes>
<noscript>
<s>
<samp>
<small>
<span>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<var>
HTML ,
. DOM Level 2 HTML
, HTML
JavaScript. , T
HTMLTElement. , <head> HTMLHeadEle
ment.
, <h1> <h6>,
HTMLHeadingElement.
,
JavaScript HTML. JavaScript
, , (, id)
826
HTMLElement
, (,
longDesc). HTML Java Java
Script, . , for <label> <script>
htmlFor HTMLLabelElement HTMLScriptElement, . .
for .
HTML, HTML,
.
HTML,
HTMLElement. DOM
, .
, . ,
, ,
.
HTML 4 (*).
HTML
,
, HTML.
, , ,
, <form> <input>.
, HTML
Element. . , Anchor, Applet, Canvas,
Form, Image, Input, Link, Option, Select, Table Textarea.
HTML2
, DOM
<a>
<applet>
<area>
<base>
<basefont>
<br>
HTMLBRElement: clear*
<button>
<caption>
HTMLTableCaptionElement: align*
<col>, <colgroup> HTMLTableColElement: align, ch, chOff, [long] span, vAlign, width
<del>, <ins>
<dir>
<div>
HTMLDivElement: align*
<dl>
<fieldset>
HTMLElement
827
HTML2 , DOM
<font>
<form>
<frame>
HTMLHeadElement: profile
<hr>
<html>
HTMLHtmlElement: version*
<iframe>
<img>
<input>
<ins>
. <del>
<isindex>
<label>
<legend>
<li>
<link>
<map>
<menu>
<meta>
<object>
<ol>
<p>
HTMLParagraphElement: align*
<param>
828
HTMLElement.onclick
HTML2 , DOM
<pre>
<q>
. <blockquote>
<script>
<select>
<style>
<table>
<tbody>,
<tfoot>,
<thead>
<td>, <th>
. <tbody>
<th>
. <t>
<thead>
. <tbody>
<title>
HTMLTitleElement: text
<tr>
<ul>
.
Anchor, Element, Form, HTMLDocument, Image, Input, Link, Node, Option, Select, Table, Table
Cell, TableRow, TableSection, Textarea; 15
HTMLElement.onclick
DOM Level 0
Function onclick
onclick HTMLElement ,
, .
HTMLElement.ondblclick
829
: onclick onmusedown .
.
HTMLElement.ondblclick
DOM Level 0
Function ondblclick
ondblclick HTMLElement ,
, .
HTMLElement.onkeydown
DOM Level 0
, ,
Function onkeydown
onkeydown HTMLElement ,
, ,
. , ,
. 17.
onkeydown
,
onkeypress.
HTMLElement.onkeypress; 17
HTMLElement.onkeypress
DOM Level 0
, ,
Function onkeypress
onkeypress HTMLElement ,
, ,
. keypress key
down keyup. keydown keyup
keypress,
keypress, keydown.
830
HTMLElement.onkeyup
,
, ,
. 17.
HTMLElement.onkeydown; 17
HTMLElement.onkeyup
DOM Level 0
, ,
Function onkeyup
onkeyup HTMLElement ,
, ,
.
HTMLElement.onkeydown; 17
HTMLElement.onmousedown
DOM Level 0
, ,
Function onmousedown
onmousedown HTMLElement ,
, .
HTMLElement.onmousemove
DOM Level 0
Function onmousemove
onmousemove HTMLElement ,
,
.
onmousemove,
. ,
.
,
mousedown mouseup.
831
HTMLElement.onmouseout
HTMLElement.onmouseout
DOM Level 0
Function onmouseout
onmouseout HTMLElement ,
,
.
HTMLElement.onmouseover
DOM Level 0
Function onmouseover
onmouseover HTMLElement ,
, .
HTMLElement.onmouseup
DOM Level 0
Function onmouseup
onmouseup HTMLElement ,
, .
HTMLElement.scrollIntoView()
.scrollIntoView(top)
top
, ,
. true
832
IFrame
, . false,
.
, ,
, , . .
.
HTML ,
, . top
, ,
, ,
. , Link Input, ,
focus() .
IFrame
<iframe> HTML#
NodeElementHTMLElementIFrame
,
IFrame Window.
IFrame, HTMLElement
:
Document contentDocument
, <iframe>.
String src
URL, .
.
src <iframe>.
, IFrame ,
HTML:
String frameBorder
frameborder
"0"
String height
height
String longDesc
longdesc
URL
String marginHeight
marginheight
String marginWidth
marginwidth
String name
name
DOM Level 0 target
String scrolling
scrolling
String width
width
833
Image
,
JavaScript <iframe> <frame>. <if
rame> frames[] .
Window,
. <if
rame> id ,
IFrame, .
content
Document, URL
src. : contentDocument
(. 13.8.2).
Frame, Window; 14
Image
HTML#
NodeElementHTMLElementImage
,
; .
String name
. <img>
name, Image
Document.
String src
, URL
, .
src <img>. URL
, .
, .
Image ,
HTML:
String alt
,
alt
long height
height
long hspace ()
hspace
834
Image
boolean isMap
ismap
String longDesc
longdesc
URI
String useMap
usemap
long vspace ()
vspace
long width
width
HTMLElement
:
onabort
, .
onerror
, .
onload
HTML
Image HTML <img>.
<img> , . . JavaScript :
<img src="url"
width=""
height=""
alt=""
[ onload="" ]
[ onerror="" ]
[ onabort="" ]
>
//
//
//
//
//
//
//
,
,
src Image .
, ,
. ,
. 22.
Image JavaScript
Image(). : ,
. ,
HTML, ,
src .
Image.
Image src.
, . ,
835
Image.onabort
URL <img>,
, , .
22
Image.onabort
Function onabort
onabort Image ,
, (,
) , .
Image.onerror
, ,
Function onerror
onerror Image ,
, .
Image.onload
Function onload
onload Image ,
, . .
Window.onload.
Input
HTML#
String accept
file, MIME,
,
. accept.
836
Input
String accessKey
( ),
.
accesskey.
String align
. align.
String alt
, ,
. alt.
boolean checked
type "radio" "checkbox",
, (
) .
. checked.
boolean defaultChecked
type "radio" "checkbox",
checked,
. , checked
.
checked .
String defaultValue
type "text", "password" "file",
, .
, .
value .
boolean disabled
true,
. disabled.
readonly HTMLFormElement form
Form, <form>,
, null, .
long maxLength
type "text" "password",
,
. size. max
length.
String name
, name.
.
boolean readOnly
true type "text"
"password", .
readonly.
Input
837
blur()
.
click()
type "button", "checkbox", "radio",
"reset" "submit" .
focus()
.
select()
type "file", "password" "text"
, .
,
.
onblur
, .
838
Input
onchange
,
,
Tab ,
.
.
( )
( onclick) .
onclick
, ,
, .
onfocus
, .
Input
839
. ,
, value,
, ,
, . ( ,
multipart/formdata POST.)
HTML
JavaScript , .
HTML value JavaScript val
ue ,
.
, onchange.
"hidden"
. value
,
. ,
.
"image"
,
( src),
. value .
"submit".
"password"
,
. , , (
),
. ,
: ,
.
value.
password text.
onchange, .
"radio"
.
.
,
(
).
<form>
name. , ,
checkbox. :
( , )
HTML <select> (. Select).
checked , .
,
, checked
. checked
onclick.
840
Input
value ,
. ,
<input>, , <label>.
"reset"
,
button, .
reset,
, (
HTML value JavaScript defaultValue).
value , .
onclick
, false
, 17.
Form.reset() Form.onreset.
"submit"
,
. value
, .
onclick
, false.
Form.submit() Form.onsubmit.
"text"
type.
. HTML value
, , JavaScript
value .
, on
change. size , maxLength
, .
text, Enter
.
<textarea>
(. Textarea).
password.
value Input
, ,
, .
type value
. text file
, . button, reset submit
value .
, checkbox, radio image, value
.
name Input , .
name.
841
Input.blur()
. , .
:
=
.
, .
, name
JavaScript. ,
. . ,
, address ,
zip, address.zip .
radio checkbox
name .
:
=1, 2,..., n
JavaScript,
, . ,
Checkbox options order JavaScript
order.options[].
<input> .
<button>, <select> <textarea>.
Input.blur()
void blur()
blur()
onblur; , focus().
blur() ,
focus(), onblur.
,
, focus() .
Input.click()
void click()
click() ,
onclick .
842
Input.focus()
click() . on
click, button
, onclick. click()
submit reset ,
submit() reset() Form.
Input.focus()
void focus()
focus() ,
onfocus,
. , focus()
text, , , .
focus() button,
.
Input.onblur
DOM Level 0
Function onblur
onblur Input , ,
. blur()
onblur
. , focus()
onblur
, .
Element.addEventListener(), Window.onblur; 17
Input.onchange
Function onchange
onchange Input ,
, ,
. ,
text, password file, radio checkbox
( onclick
onchange). :
843
Input.onclick
, , ,
JavaScript.
, , onchange
. onchange
; ,
. ,
,
, ,
.
HTMLElement.onkeypress.
onchange button, hidden, image,
reset submit. on
click.
Element.addEventListener(), HTMLElement.onkeypress; 17
Input.onclick
Function onclick
onclick Input ,
, .
, onclick ,
, .
onclick click().
: reset submit ,
:
, . onclick
, ,
. ,
, false
, 17.
: onsub
mit onreset Form.
Element.addEventListener(); 17
Input.onfocus
Function onfocus
onfocus Input ,
, . focus()
844
Input.select()
onfocus
.
Element.addEventListener(), Window.onfocus; 17
Input.select()
void select()
JSObject
Java# Java#
Java# JavaScript#
call()
JavaScript.
eval()
JavaScript JavaScript.
getMember()
JavaScript.
getSlot()
JavaScript.
getWindow()
JSObject, JavaScript Window
.
removeMember()
JavaScript.
setMember()
JavaScript.
setSlot()
JavaScript.
845
JSObject.call()
toString()
toString() JavaScript .
JSObject.call()
Java# Java#
JavaScript#
JavaScript.
[]
Java,
.
Java, JavaScript.
JSObject.eval()
Java# Java#
JavaScript#
, JavaScript,
.
846
JSObject.getMember()
JavaScript s,
Java.
JSObject.getMember()
Java# Java#
JavaScript#
, .
Java, Java
JSObject.
JSObject.getSlot()
Java# Java#
JavaScript#
, .
JavaScript.
847
JSObject.getWindow()
JSObject.getWindow()
Java# Java#
JSObject
Applet, ,
JSObject.
JSObject, JavaScript Window ,
.
JSObject.removeMember()
Java# Java#
JavaScript#
, JSObject.
JSObject.setMember()
Java# Java#
JavaScript#
JSObject .
, .
848
JSObject.setSlot()
JSObject.setSlot()
Java# Java#
JavaScript#
, JSObject.
, .
JSObject.toString()
Java# Java#
JavaScript#
KeyEvent
Firefox
EventUIEventKeyEvent
849
Layer
Event, UIEvent; 17
Layer
Netscape 4; Netscape 6
Netscape
Layer Netscape 4
HTML.
.
16
Link
HTML#
DOM Level 0
NodeElementHTMLElementLink
850
Link
URL.
() URL:
http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
String hash
URL ,
(#), : "#result". URL
, Link. HTML
,
name <a> (. Anchor).
String host
URL , ,
: "www.oreilly.com:1234".
String hostname
URL , : "www.oreilly.com".
String href
URL
Link, URL.
String pathname
URL , : "/catalog/search.html".
String port
URL , : "1234".
String protocol
URL ,
, : "http:".
String search
URL , ,
, : "?q=JavaScript&m=10".
, URL,
Link , <a> <area>:
String charset
charset
String coords
coords
<area>
String name
name
. .
Anchor
String rel
rel
String rev
rev
String shape
shape
<area>
long tabIndex
tabIndex
851
Link
String target
target
,
String type
type
blur()
.
focus()
, ,
.
Link :
onclick
, .
onmouseout
, .
onmouseover
, .
HTML
Link <a> </a>.
Link href . name,
Anchor:
<a href="url"
[ name="" ]
[ target="_" ]
[ onclick="" ]
[ onmouseover="" ]
[ onmouseout="" ]
>
</a>
//
//
//
//
//
//
//
Anchor
Link HTML.
<a> href,
<area> . href
<a> name,
Anchor, Link. .
Anchor.
( <a> <area>)
Link links[] Document.
, , URL,
Link URL. Link Location,
URL.
852
Link.blur()
// URL
var url = document.links[0].href;
Anchor, Location
Link.blur()
DOM Level 0
void blur()
, ,
.
Link.focus()
DOM Level 0
void focus()
,
. ,
.
Link.onclick
DOM Level 0
Function onclick
onclick Link ,
, .
, .
, false
, 17.
Element.addEventListener(), MouseEvent; 17
Link.onmouseout
, ,
Function onmouseout
DOM Level 0
853
Link.onmouseover
onmouseout Link ,
, .
onmouseover.
Link.onmouseover
DOM Level 0
, ,
Function onmouseout
onmouseover Link , ,
.
, URL
.
, ,
. (,
)
.
Location
JavaScript 1.0
ObjectLocation
location
.location
Location URL
.
() URL:
http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
hash
, URL,
(#), "#result". URL
.
host
, URL
, , "www.oreilly.com:1234".
hostname
, URL
, "www.oreilly.com".
854
Location
href
, URL
, Location,
URL. URL
, URL.
pathname
, URL,
"/catalog/search.html".
port
( ) ,
URL , "1234".
protocol
, URL
, , "http:".
search
, URL,
, ,
"?q=JavaScript&m=10".
reload()
.
replace()
,
.
855
Location.reload()
URL Location .
reload() , replace()
.
Location.reload()
JavaScript 1.1
location.reload()
location.reload()
, , ,
,
. false,
, .
reload() Location , ,
Location. false
, , HTTP IfModi
fiedSince. , reload
, , . ,
, .
reload() , true,
. , ,
, Shift.
Location.replace()
JavaScript 1.1
location.replace(url)
url
, URL ,
.
replace() Location .
loca
tion location.href , replace()
History. URL
856
MimeType
History. replace()
URL, .
History
MimeType
JavaScript 1.1; IE
MIME
ObjectMimeType
navigator.mimeTypes[i]
navigator.mimeTypes[""]
navigator.mimeTypes.length
description
, ,
() , MimeType.
enabledPlugin
Plugin,
, MIME
. , null.
suffixes
, (
, .),
MIME. , MIME text/html :
"html, htm".
type
, MIME
MIME , : "text/html" "image/jpeg".
.
type
navigator.mimeTypes[].
MimeType MIME (. . ),
.
,
. MimeType mimeTypes[]
Navigator. IE mimeTypes[]
.
navigator.mimeTypes[]
MIME ( type). ,
MIME ,
. ,
, :
var show_movie = (navigator.mimeTypes["video/mpeg"] != null);
857
MouseEvent
Navigator, Plugin
MouseEvent
initMouseEvent()
MouseEvent.
858
MouseEvent.initMouseEvent()
Event,
click, mousedown, mousemove, mouseout, mouseover mouseup. :
UIEvent Event.
Event, UIEvent; 17
MouseEvent.initMouseEvent()
MouseEvent
MouseEvent, , Event UIEvent.
, ,
.
Mouse
Event. MouseEvent, Docu
ment.createEvent(), , EventTar
get.dispatchEvent().
Navigator
navigator
JavaScript 1.0
ObjectNavigator
Navigator
859
appCodeName
, .
, Netscape (Netscape, Mozilla, Firefox),
"Mozilla". Microsoft "Mozilla".
appName
, . ,
Netscape, "Netscape". Inter
net Explorer "Microsoft Internet Explorer".
.
appVersion
,
. .
, parseInt(),
parseFloat().
, , .
, , .
cookieEnabled
, true,
cookie, false, .
mimeTypes[]
MimeType, MIME
(, text/html image/gif), .
MIME. mimeTypes[]
Internet Explorer, , . . IE MimeType.
platform
, /
, .
, : "Win32",
"MacPPC" "Linux i586".
plugins[]
Plugin,
, . Plugin
, MIME.
plugins[] Internet Explorer, , . . IE
Plugin.
userAgent
, ,
useragent HTTP.
navigator.appCodeName,
navigator.appVersion. :
Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)
860
Navigator.javaEnabled()
navigator.javaEnabled()
, Java Java
.
Navigator , .
. , , Netscape Navigator,
, JavaScript, .
Navigator,
navigator Window.
Navigator ,
,
. 14.3 ,
, Navigator.
, ,
13.6.3.
MimeType, Plugin
Navigator.javaEnabled()
JavaScript 1.1
, Java
navigator.javaEnabled()
true, Java , false,
.
navigator.javaEnabled() ,
Java , , Java.
Node
Node .
Node nodeType, ,
.
; . :
Node();
Node
861
862
Node
appendChild()
, childNodes[]
. ,
.
Node
863
cloneNode()
.
hasAttributes() [DOM Level 2]
true, Element .
hasChildNodes()
true, .
insertBefore()
. ,
.
isSupported() [DOM Level 2]
true,
.
normalize()
Text Text.
removeChild()
( ) .
replaceChild()
( ) ,
.
selectNodes() [ IE]
, IE, XPath,
, NodeList.
, DOM,
Document.evaluate() Document.crea
teExpression().
selectSingleNode() [ IE]
, IE, XPath,
, .
, DOM,
Document.evaluate() Document.crea
teExpression().
transformNode() [ IE]
, IE, XSLT
. ,
, IE,
XSLTProcessor.
transformNodeToObject() [ IE]
, IE, XSLT
Document.
, , IE,
XSLTProcessor.
864
Node
( Document)
Node,
. ( Internet Explorer Node
XML, XPath
XSLT. . 21.)
parentNode childNodes[]
. ,
childNodes[] firstChild nextSibling (
lastChild previousSibling ). append
Child(), insertBefore(), removeChild() replaceChild()
, .
Node,
, Element Text. nodeType
, .
,
. :
var n;
// ,
if (n.nodeType == 1) {
// Node.ELEMENT_NODE
var tagname = n.tagName; // Element,
}
nodeName nodeValue , ,
, nodeType. :
( tag
Name Element data Text)
:
nodeType
nodeName
nodeValue
ELEMENT_NODE
null
ATTRIBUTE_NODE
TEXT_NODE
#text
CDATA_SECTION_NODE
#cdatasection
PROCESSING_INSTRUCTION_NODE
COMMENT_NODE
#comment
DOCUMENT_NODE
#document
null
DOCUMENT_TYPE_NODE
null
DOCUMENT_FRAGMENT_NODE
#documentfragment
null
.
Document, Element, Text, XMLSerializer, XPathExpression, XSLTProcessor; 15
865
Node.appendChild()
Node.appendChild()
Node appendChild(Node )
throws DOMException;
, . DocumentFragment,
, .
.
DOMException
:
HIERARCHY_REQUEST_ERR
( ).
WRONG_DOCUMENT_ERR
ownerDocument ownerDocu
ment .
NO_MODIFICATION_ALLOWED_ERR
,
.
,
.
, .
DocumentFragment, ,
childNodes[] Document
Fragment. , (
) . ownerDocu
ment ownerDocument .
:
function appendMessage(message) {
var pElement = document.createElement("p");
var messageNode = document.createTextNode(message);
pElement.appendChild(messageNode); //
document.body.appendChild(pElement); //
}
866
Node.cloneNode()
Node.cloneNode()
()
Node cloneNode(boolean );
true, cloneNode()
. .
.
cloneNode() , , .
true, .
, .
, parentNode
null. Element, .
, , ,
.
Node.hasAttributes()
boolean hasAttributes();
true, , false,
. : Element .
Node.hasChildNodes()
boolean hasChildNodes();
true, , false,
.
867
Node.insertBefore()
Node.insertBefore()
Node insertBefore(Node ,
Node )
throws DOMException;
, . DocumentFragment,
.
,
. null,
.
.
DOMException
code:
HIERARCHY_REQUEST_ERR
, (
).
WRONG_DOCUMENT_ERR
ownerDocument .
NO_MODIFICATION_ALLOWED_ERR
.
NOT_FOUND_ERR
.
. childNodes[] ,
. null,
childNodes[] ,
appendChild(). :
, .
,
.
DocumentFragment, ;
.
868
Node.isSupported()
:
function insertMessage(message) {
var paragraph = document.createElement("p"); // <p>
var text = document.createTextNode(message); // Text
paragraph.appendChild(text);
//
//
document.body.insertBefore(paragraph, document.body.firstChild)
}
Node.isSupported()
boolean isSupported(String ,
String );
(
).
true, ,
false, .
W3C DOM ,
. ,
.
DOMImplementa
tion.hasFeature().
DOMImplementation.hasFeature()
Node.normalize()
Text
void normalize();
,
Text Text .
.
869
Node.removeChild()
Text
Node.removeChild()
( )
Node removeChild(Node )
throws DOMException;
DOMException
:
NO_MODIFICATION_ALLOWED_ERR
.
NOT_FOUND_ERR
.
childNodes[] .
, , . remove
Child() .
.
:
document.body.removeChild(document.body.lastChild);
Node.replaceChild()
Node replaceChild(Node ,
Node )
throws DOMException;
870
Node.selectNodes()
, .
DOMException
code:
HIERARCHY_REQUEST_ERR
( ).
WRONG_DOCUMENT_ERR
ownerDocument ownerDocu
ment .
NO_MODIFICATION_ALLOWED_ERR
.
NOT_FOUND_ERR
.
.
, , .
, childNodes[]
.
,
.
DocumentFragment, ; ,
, Docu
mentFragment.
n <b>,
<b>, :
//
var n = document.getElementsByTagName("p")[0].firstChild;
var b = document.createElement("b"); // <b>
n.parentNode.replaceChild(b, n);
// <b>
b.appendChild(n);
// <b>
Node.selectNodes()
XPath#
NodeList selectNodes(String )
IE 6
Node.selectSingleNode()
871
XPath.
NodeList, , .
, IE, XPath,
,
NodeList. selectNodes() XML,
HTML. : Document
, XML.
, ,
Document.evaluate().
Document.evaluate(), XPathExpression; 21
Node.selectSingleNode()
IE 6
, XPath#
Node selectSingleNode(String )
XPath.
Node, , null, ,
.
, IE, XPath,
.
null, , . selectSingle
Node() XML, HTML.
: Document ,
XML.
, ,
Document.evaluate().
Document.evaluate(), XPathExpression; 21
Node.transformNode()
XSLT
IE 6
872
Node.transformNodeToObject()
xslt
XSLT, Document.
,
.
, IE,
XSLT
. transformNode()
XML, HTML. :
Document ,
XML.
XSLT
Processor.
XSLTProcessor, Node.transformNodeToObject(); 21
Node.transformNodeToObject()
IE 6
XSLT
xslt
XSLT, Document.
Document.
, IE,
XSLT
Document. transformNodeToObject()
XML, HTML. :
Document ,
XML.
XSLT
Processor.
XSLTProcessor, Node.transformNodeToObject(); 21
NodeList
ObjectNodeList
873
NodeList.item()
item()
.
NodeList
(. . ) Node. length ,
, item() .
NodeList Node: NodeList
(null) .
JavaScript NodeList , JavaScript,
,
item(). NodeList
. NodeList
JavaScript, NodeList
Element[] Node[] (. . Element Node).
Document.getElementsByTagName(), Element.getElementsByTagName() HTMLDocu
ment.getElementsByName() Element[],
NodeList. childNodes Node
NodeList, Node Node[],
childNodes[].
: NodeList :
. , NodeList
, ,
NodeList. Node
List, (,
), NodeList!
Document, Element
NodeList.item()
NodeList
( ) NodeList. NodeList
0, length1.
NodeList null,
NodeList.
874
Option
Option
Select
Option Document.createElement(),
. , DOM Level 0 Option
Option():
new Option(String , String ,
boolean , boolean )
, text
Option.
, value
Option.
, defaultSe
lected Option.
, selected
Option.
boolean defaultSelected
selected <option>.
selected
. selected.
boolean disabled
true , <option>
. disabled.
readonly HTMLFormElement form
<form>, .
readonly long index
<option> <select>.
String label
, . label.
, ,
<option>.
boolean selected
: true .
selected.
875
Packages
HTML
Option <option> <select>,
<form>. <select> <option>:
<form ...>
<select ...>
<option
[ value="" ] // ,
[ selected ] >
// ,
_
// ,
[ </option> ]
...
</select>
...
</form>
Option Select.
, ,
, , options[]
Select, ,
.
: , , <op
tion>, HTML
, ,
HTML .
Option
Select Option(). Op
tion, Select
Select.add().
Select.options[].
Select, Select.options[]; 18
Packages
. Packages III
Password
. Input
876
Plugin
Plugin
JavaScript 1.1; IE
ObjectPlugin
navigator.plugins[i]
navigator.plugins['']
description
,
.
,
.
filename
, ,
.
. ,
filename, name.
length
Plugin MimeType,
, .
, length .
name
name Plugin ,
. .
navigator.plug
ins[]. , ,
:
var flash_installed = (navigator.plugins["Shockwave Flash"] != null);
Plugin MimeType,
, . length
MimeType .
, (plugin), ,
, .
Plugin, plugins[] Navigator Plugin,
, . IE
Plugin navigator.plugins[] .
navigator.plugins[]
,
(, ,
MIME , ).
. , ,
877
ProcessingInstruction
,
:
var flash_installed = (navigator.plugins["Shockwave Flash"] != null);
,
name Plugin.
, ,
. Plugin
, MimeType,
, .
: Plugin Navigator ,
Plugin MimeType.
, :
navigator.plugins[i][j]
// j MIME i
navigator.plugins["LiveAudio"][0] // MIME LiveAudio
, , Plugin
MIME, ,
enabledPlugin MimeType ,
MIME.
Navigator, MimeType
ProcessingInstruction
XML#
String data
(. .
?>, ).
readonly String target
. ,
<?; ,
.
XML
. , HTML,
ProcessingInstruction.
Document.createProcessingInstruction()
Radio
. Input
Range
878
Range
,
Range.
compareBoundaryPoints(). . Range.compare
BoundaryPoints().
unsigned short START_TO_START = 0
.
unsigned short START_TO_END = 1
.
unsigned short END_TO_END = 2
.
unsigned short END_TO_START = 3
.
Range . :
.
; setEnd()
setStart(). , , detach()
Range
DOMException INVALID_STATE_ERR.
readonly boolean collapsed
true, ,
. . .
readonly Node commonAncestorContainer
, (. .
) , .
readonly Node endContainer
, .
readonly long endOffset
endContainer.
readonly Node startContainer
, .
readonly long startOffset
startContainer.
, Range. :
detach() ,
DOMException INVALID_STATE_ERR.
,
Range:
cloneContents()
DocumentFragment,
, Range.
Range
879
cloneRange()
Range, ,
.
collapse()
, , .
compareBoundaryPoints()
1, 0 1 .
, ,
.
deleteContents()
, Range.
detach()
, ,
. ,
DOMException INVALID_STATE_ERR.
extractContents()
, Range,
DocumentFragment.
cloneContents() deleteContents().
insertNode()
.
selectNode()
,
.
selectNodeContents()
,
, .
setEnd()
.
setEndAfter()
.
setEndBefore()
.
setStart()
.
setStartAfter()
.
setStartBefore()
.
880
Range.cloneContents()
surroundContents()
,
.
toString()
,
Range.
Range , , ,
. Range (
Range Firefox Opera, Safari
, Internet Explorer ), Document
createRange(), Range.
: Internet Explorer Docu
ment.createRange(), , ,
Range. Range
.
: .
. Element,
Document Text. Element Document
. 0
. 1
. Text,
.
Range
.
. ,
DocumentFragment.
, deleteContents(), ex
tractContents(), cloneContents() insertNode() ,
.
, Range,
, ,
(
) .
Document.createRange(), DocumentFragment
Range.cloneContents()
DocumentFragment
DocumentFragment cloneContents()
throws DOMException;
881
Range.cloneRange()
DocumentFragment,
.
DocumentType,
DOMException HIERARCHY_REQUEST_ERR.
Docu
mentFragment.
Range.cloneRange()
Range cloneRange();
Range, , .
Document.createRange()
Range.collapse()
void collapse(boolean )
throws DOMException;
true,
.
.
.
.
, , . .
. , collapsed true.
Range.compareBoundaryPoints()
882
Range.deleteContents()
, (. .
). ,
Range.
, .
1,
, ; 0,
, 1,
, .
,
DOMException WRONG_DOCUMENT_ERR.
,
, ,
. ,
.
:
Range.START_TO_START
Range.
Range.END_TO_END
Range.
Range.START_TO_END
.
Range.END_TO_START
.
,
. ,
,
,
. Range.START_TO_END
. Range.END_TO_START
.
Range.deleteContents()
void deleteContents()
throws DOMException;
883
Range.detach()
, ,
, DOMException NO_MODIFICA
TION_ALLOWED_ERR.
, .
, .
: Text,
Node.normalize().
clone
Contents(),
extractContents().
Node.normalize(),Range.cloneContents(), Range.extractContents()
Range.detach()
Range
void detach()
throws DOMException;
DOM Range, , . .
.
, Range , detach(),
, .
: detach() Range
. detach() ,
,
Range .
Range.extractContents()
DocumentFragment
DocumentFragment extractContents()
throws DOMException;
DocumentFragment, .
884
Range.insertNode()
DOMException NO_MODIFICATION_ALLOWED_ERR,
,
HIERARCHY_REQUEST_ERR, DocumentType.
DocumentFragment,
( ).
, ,
Text ( Node.normalize()).
Range.insertNode()
void insertNode(Node )
throws RangeException, DOMException;
, .
RangeException INVALID_NODE_TYPE_ERR,
Attr, Document, Entity Notation.
DOMException
:
HIERARCHY_REQUEST_ERR
, ,
.
NO_MODIFICATION_ALLOWED_ERR
, ,
.
WRONG_DOCUMENT_ERR
, .
( )
. ,
. ,
.
DocumentFragment, ,
.
, , Text,
. Text,
885
Range.selectNode()
Text.
Node.normalize().
DocumentFragment, Node.normalize()
Range.selectNode()
void selectNode(Node )
throws RangeException, DOMException;
, (. . ,
).
,
. . .
Range.selectNodeContents()
Range.selectNodeContents()
void selectNodeContents(Node )
throws RangeException, DOMException;
, .
DocumentType, Entity
Notation, RangeException INVALID_NODE_TYPE_ERR.
, ,
Range, DOMException
WRONG_DOCUMENT_ERR.
886
Range.setEnd()
,
.
Range.selectNode()
Range.setEnd()
void setEnd(Node ,
long )
throws RangeException, DOMException;
, .
RangeException INVALID_NODE_TYPE_ERR,
DocumentType.
DOMException WRONG_DOCUMENT_ERR,
, ,
Range, INDEX_SIZE_ERR,
.
endContainer endOffset.
Range.setEndAfter()
void setEndAfter(Node )
throws RangeException,DOMException;
, .
RangeException INVALID_NODE_TYPE_ERR,
Document, DocumentFragment Attr
Document, DocumentFragment Attr.
887
Range.setEndBefore()
DOMException WRONG_DOCUMENT_ERR,
, ,
Range.
.
Range.setEndBefore()
void setEndBefore(Node )
throws RangeException, DOMException;
, .
,
Range.setEndAfter(). . .
.
Range.setStart()
void setStart(Node ,
long )
throws RangeException, DOMException;
, .
,
Range.setEnd(). . .
startContainer startOffset.
888
Range.setStartAfter()
Range.setStartAfter()
DOM Level 2 Range
void setStartAfter(Node )
throws RangeException, DOMException;
, .
,
Range.setEndAfter(). . .
.
Range.setStartBefore()
void setStartBefore(Node )
throws RangeException, DOMException;
, .
,
Range.setEndAfter(). . .
.
Range .surroundContents()
void surroundContents(Node )
throws RangeException, DOMException;
, .
Range.toString()
889
DOMException RangeException
:
DOMException.HIERARCHY_REQUEST_ERR
.
DOMException.NO_MODIFICATION_ALLOWED_ERR
.
DOMException.WRONG_DOCUMENT_ERR
Document.
RangeException.BAD_BOUNDARYPOINTS_ERR
( Text),
.
RangeException.INVALID_NODE_TYPE_ERR
Document, DocumentFragment, DocumentType, Attr, Entity
Notation.
. , ,
<b>
<span>.
,
.
.
Range.toString()
String toString();
.
RangeException
, API Range
code Ran
geException. :
RangeException, .
890
Reset
RangeException Range,
. :
, Range, DOMException.
RangeException ,
DOMException .
Reset
. Input
Screen
JavaScript 1.2
ObjectScreen
screen
availHeight
( ),
. Windows
, ,
.
availWidth
( ),
. Windows
, ,
.
colorDepth
.
height
( ), .
. availHeight.
891
Select
width
( ), .
. availWidth.
screen Window
Select
892
Select
String name
name
long size
size
long tabIndex
tabindex
,
Tab
add()
Option options ,
.
blur()
.
focus()
.
remove()
<option> .
onchange
, .
HTML
Select HTML <select>. ,
Select, <option>:
<form>
...
<select
name="" // , ; name
[ size="" ] // Select
[ multiple ] // ,
[ onchange="" ] //
>
<option value="1" [selected]> _1
<option value="2" [selected]> _2
//
</select>
...
</form>
893
Select.add()
,
.
Select .
, size , 1,
multiple, size .
size , , ,
. , size 1
multiple ,
, .
,
. ,
.
options[] Select.
Option, , Select.
length ( options.length). .
Option.
Select multiple, ,
, selectedIndex.
,
. ,
options[] selected Option.
, Select, .
add() Option(),
remove(). ,
options[].
Select.add()
<option>
void add(HTMLElement ,
HTMLElement )
throws DOMException;
Option.
options, .
null, options.
DOMException NOT_FOUND_ERR,
, options.
894
Select.blur()
<option>. Op
tion, <option>.
Option, .
<optgroup>, .
null,
<select>.
Option
Select.blur()
void blur();
Select.focus()
void focus();
<select>,
,
.
Select.onchange()
DOM Level 0
Function onchange
onchange Select ,
, .
,
selectedIndex Select selected Option.
Element.addEventListener().
Element.addEventListener(), Option; 17
895
Select.options[]
Select.options[]
Select
options[] HTMLCollection,
Option, ,
Select.
options[] HTMLCollection.
, ,
Select:
options.length 0, Select
.
options.length ,
Select , ,
, .
options[] null,
Select, , ,
, ,
.
Option Option() (.
Option),
Select,
options[]. options[op
tions.length] (. Select.add()).
Option
Select.remove()
<option>
void remove(long );
<option> options.
<option>,
options. , re
move() .
Option
896
Style
Style
. CSS2Properties
Submit
. Input
Table
<table> HTML#
NodeElementHTMLElementTable
HTMLElement caption
<caption> null, .
readonly HTMLCollection rows
(HTMLCollection) TableRow, .
, <thead>, <tfoot> <tbody>.
readonly HTMLCollection tBodies
(HTMLCollection) TableSection,
<tbody> .
TableSection tFoot
<tfoot> null, .
TableSection tHead
<thead> null, .
, HTML
<table>.
String align
()
align
String bgColor
()
bgcolor
String border
border
String cellPadding
cellpadding
String cellSpacing
cellspacing
String frame
frame
String rules
rules
String summary
summary
String width
width
createCaption()
<caption> ( )
, .
Table.createCaption()
897
createTFoot()
<tfoot> (
) , .
createTHead()
<thead> (
) , .
deleteCaption()
<caption> , .
deleteRow()
.
deleteTFoot()
<tfoot> , .
deleteTHead()
<thead> , .
insertRow()
, <tr> .
Table.createCaption()
<caption>
HTMLElement createCaption();
HTMLElement, <caption> () .
, .
, () <caption>, ,
.
Table.createTFoot()
<tfoot>
HTMLElement createTFoot();
TableSection, <tfoot> ( )
. , .
898
Table.createTHead()
, ()
<tfoot>, , .
Table.createTHead()
<thead>
HTMLElement createTHead();
TableSection, <thead> ( ,
) . ,
. ,
() <thead>, , .
Table.deleteCaption()
<caption>
void deleteCaption();
<caption>, ,
.
Table.deleteRow()
void deleteRow(long )
throws DOMException;
DOMException INDEX_SIZE_ERR,
.
.
, .
<thead> <tfoot> .
TableSection.deleteRow()
Table.deleteTFoot()
Table.deleteTFoot()
899
DOM Level 2 HTML
<tfoot>
void deleteTFoot();
<tfoot>, .
, .
Table.deleteTHead()
<thead>
void deleteTHead();
<thead>, .
, .
Table.insertRow()
HTMLElement insertRow(long )
throws DOMException;
, .
TableRow, .
DOMException INDEX_SIZE_ERR,
.
TableRow, <tr>,
.
, , .
, .
, <tbody>,
, , .
900
TableCell
TableRow.insertCell().
TableSection.insertRow()
TableCell
NodeElementHTMLElementTableCell
String abbr
abbr
. HTML
String align
align
String axis
axis
. HTML
String ch
ch
String chOff
choff
long colSpan
colspan
String headers
headers
id
String height ()
height
long rowSpan
rowspan
String scope
scope
String vAlign
valign
String width ()
width
TableRow
<tr> HTML#
901
TableRow.deleteCell()
readonly long rowIndex
.
String align
align
,
String bgColor ()
bgcolor
String ch
ch
String chOff
choff
String vAlign
valign
deleteCell()
.
insertCell()
<td> .
HTML.
TableRow.deleteCell()
void deleteCell(long )
throws DOMException;
DOMException INDEX_SIZE_ERR,
.
902
TableRow.insertCell()
TableRow.insertCell()
<td>
HTMLElement insertCell(long )
throws DOMException;
, .
TableCell, <td>.
DOMException INDEX_SIZE_ERR,
, .
<td> .
,
, .
, .
:
<td>. ,
<th> Document.createElement() Node.insertBe
fore() .
TableSection
NodeElementHTMLElementTableSection
,
STRING
CH
ch
903
TableSection.deleteRow()
deleteRow()
.
insertRow()
.
TableSection.deleteRow()
void deleteRow(long )
throws DOMException;
DOMException INDEX_SIZE_ERR,
.
().
:
, .
Table.deleteRow()
TableSection.insertRow()
HTMLElement insertRow(long )
throws DOMException;
, .
TableRow, <tr>.
904
Text
DOMException INDEX_SIZE_ERR,
.
<tr>
. ,
.
, ,
. :
, .
Table.insertRow()
Text
HTML# XML#
NodeCharacterDataText
CDATASection
splitText()
Text
.
CharacterData, Node.normalize()
Text.splitText()
Text
, Text.
905
Textarea
Text, .
DOMException
:
INDEX_SIZE_ERR
Text Comment.
NO_MODIFICATION_ALLOWED_ERR
.
Text . Text
, ,
. ,
( ) . Text
, . , Text
,
.
CDATASection Text, splitText()
CDATASection,
CDATASection, Text.
Node.normalize()
Textarea
String defaultValue
. ,
.
.
readonly Form form
Form, <form>,
Textarea, null, .
readonly String type
.
Input. "textarea".
String value
.
defaultValue.
Textarea, value
. value ,
Textarea. value ,
.
906
Textarea
Textarea ,
HTML:
cols
String name
;
name
long rows
rows
long tabIndex
tabindex
blur()
.
focus()
.
select()
.
onchange
, Textarea
.
Textarea,
.
HTML
Textarea HTML <textarea> </text
area>:
<form>
...
<textarea
[ name="" ]
// ,
[ rows="" ]
//
[ cols="" ]
//
[ onchange="" ] // onchange()
>
_
// ; defaultValue
</textarea>
...
</form>
907
Textarea.blur()
Form, Input; 18
Textarea.blur()
void blur();
Textarea.focus()
void focus();
,
.
Textarea.onchange()
DOM Level 0
Function onchange
onchange Textarea ,
,
, .
: onchange , value
Text JavaScript. , ,
. ,
,
HTMLElement.onkeypress.
Element.addEventListener().
908
Textarea.select()
.
Element.addEventListener(), HTMLElement.onkeypress, Input.onchange; 17
Textarea.select()
void select();
, <textarea>.
,
.
TextField
. Input
UIEvent
EventUIEvent
KeyEvent, MouseEvent
initUIEvent()
UIEvent, ,
Event.
UIEvent Event,
Event, DOMFocusIn, DOMFocusOut DOMActivate.
,
UIEvent MouseEvent.
UIEvent.initUIEvent()
UIEvent.initUIEvent()
909
DOM Level 2 Events
UIEvent
typeArg
.
canBubbleArg
.
cancelableArg
preventDefault().
viewArg
, .
detailArg
detail .
Window
#
JavaScript 1.0
ObjectGlobalWindow
self
window
window.frames[i]
Window ,
JavaScript (. Global III
):
closed
, , .
, Window
910
Window
. Window , closed
true.
defaultStatus
, ,
. .
Window.defaultStatus.
document
Document,
, . .
Document.
event [ IE]
Internet Explorer Event,
.
IE. DOM Event
.
Event, 17.
frames[]
Window, <iframe>,
. frames.length
frames[]. : , frames[],
frames[].
history
History .
. History.
innerHeight, innerWidth
,
. ,
. IE,
clientHeight client
Width document.documentElement document.body (
IE). 14.3.1.
location
Location . URL
. URL
URL .
Location.
name
, . ,
open() name <frame>.
target <a> <form>.
target , ,
,
.
navigator
, Naviga
tor, .
. Navigator.
Window
911
opener
, Window,
, open()
. Window,
, ,
. opener ,
, .
outerHeight, outerWidth
,
. ,
, , .
IE,
.
pageXOffset, pageYOffset
, ,
(pageXOffset) (pageYOffset).
Internet Explorer,
scrollLeft scrollTop document.documentElement
document.body ( IE).
14.3.1.
parent
Window,
. , parent
. , parent ,
.
screen
Screen,
,
. . Screen.
screenLeft, screenTop, screenX, screenY
,
. IE, Safari Opera screenLeft
screenTop, Firefox Safari screenX screenY.
self
. window.
status
,
. . Window.status.
top
,
. , top
. ,
top , .
parent.
window
window self .
912
Window
Window ,
, JavaScript ( .
Global ).
addEventListener()
.
, IE.
IE attachEvent().
alert()
.
attachEvent()
. , IE add
EventListener().
blur()
.
clearInterval()
.
clearTimeout()
.
close()
.
confirm()
.
detachEvent()
.
removeEventListener(),
IE.
focus()
;
.
getComputedStyle()
CSS, .
moveBy()
.
moveTo()
.
open()
.
print()
.
prompt()
.
Window
913
removeEventListener()
. ,
IE. Internet Explorer detachEvent().
resizeBy()
.
resizeTo()
.
scrollBy
.
scrollTo()
.
setInterval()
.
setTimeout()
.
onblur
, .
onerror
JavaScript.
onfocus
, .
onload
, ( ) .
onresize
.
onunload
, .
Window . 14.
JavaScript Window
, Window.
,
,
. , window.document document.
,
, alert() window.alert().
Window ,
JavaScript. . Global
.
Window window self, .
.
914
Window.addEventListener()
( ) :
parent
//
self.parent //
w.parent
// w
, ( ):
top
//
self.top //
f.top
// f
Window.open(). ,
open() ,
. opener
.
, Window
. alert(), confirm() prompt(),
.
Window 14,
,
.
Document; Global ; 14
Window.addEventListener()
. Element.addEventListener()
Window.alert()
JavaScript 1.0
window.alert()
( HTML) , ,
window.
alert() .
OK, ,
Window.attachEvent()
915
. alert()
, JavaScript ,
.
, alert() ,
.
,
, .
alert() , , ,
,
. alert() ,
,
177 !.
: , ,
, HTML.
\n, .
,
,
.
Window.confirm(), Window.prompt()
Window.attachEvent()
. Element.attachEvent()
Window.blur()
JavaScript 1.1
window.blur()
blur() ,
Window. ,
. /
.
Window.focus()
Window.clearInterval()
window.clearInterval(intervalId)
JavaScript 1.2
916
Window.clearTimeout()
intervalId
, setInterval().
clearInterval() ,
setInterval(). intervalId
, setInterval().
Window.setInterval()
Window.clearTimeout()
JavaScript 1.0
window.clearTimeout(timeoutId)
timeoutId
, setTimeout()
.
clearTimeout() , setTimeout().
timeoutId , setTimeout()
, .
Window.setTimeout()
Window.close()
JavaScript 1.0
window.close()
close() , window.
self.close() close().
, JavaScript.
,
.
Window.confirm()
, :
window.confirm()
JavaScript 1.0
Window.defaultStatus
917
( HTML) , .
, .
true, OK, false,
.
confirm() ,
OK , .
OK, confirm() true.
, confirm() false.
confirm() , . . ,
,
, OK .
, , JavaScript
confirm() ,
.
(,
, OK ). ,
,
OK, .
Window.alert(), Window.prompt()
Window.defaultStatus
JavaScript 1.0
window.defaultStatus
defaultStatus ;
, .
,
.
, . defaultStatus
, ,
defaultStatus, , .
, ,
, ,
defaultStatus .
defaultStatus .
Window.status.
Window.status
918
Window.detachEvent()
Window.detachEvent()
. Element.detachEvent()
Window.focus()
JavaScript 1.1
window.focus()
focus() ,
Window.
.
Window.blur()
Window.getComputedStyle()
CSS,
CSS2Properties getComputedStyle(Element ,
String );
, .
style .
,
, ,
( , ems),
.
CSS2Properties,
CSS. DOM ,
919
Window.moveBy()
, ,
, .
; ,
.
getComputedStyle() style HTMLElement,
.
,
, .
Internet Explorer
currentStyle, HTML.
CSS2Properties, HTMLElement
Window.moveBy()
JavaScript 1.2
window.moveBy(dx, dy)
dx
, .
dy
, .
moveBy() window ,
dx dy. , ,
Window.moveTo().
Window.moveTo()
JavaScript 1.2
window.moveTo(x, y)
X .
Y .
moveTo() window ,
, x y.
,
.
. ,
,
Window.open().
920
Window.onblur
Window.onblur
JavaScript 1.1
Function onblur
onblur Window ,
, .
, Java
Script, onblur <body>
<frameset>.
, Java
Script,
onblur ,
. ,
,
.
Window.onerror
JavaScript 1.1
, JavaScript
onerror :
window.onerror=
:
window.onerror(, url, )
.
url
, URL , .
, , .
true, JavaScript
; false, Java
Script .
921
Window.onfocus
onerror Window , ,
, , JavaScript,
catch. ,
onerror.
onerror , onerror
Window . :
JavaScript, onerror
onerror <body>.
onerror :
; , URL ,
, , .
, ; , ,
.
, true,
JavaScript , false,
,
.
Window.onfocus
JavaScript 1.1
Function onfocus
onfocus Window , ,
.
, Java
Script, onfocus <body>
<frameset>.
onfocus ,
onblur , ,
.
Window.onload
JavaScript 1.0
Function onload
onload Window ,
.
922
Window.onresize
, Java
Script, onload
<body> <frameset>.
onload, ,
, , ,
,
Document.
onload
Window.addEventListener() Window.attachEvent().
Window.onresize
JavaScript 1.2
Function onresize
onresize Window , ,
.
, Java
Script, onresize
<body> <frameset>, .
Window.onunload
DOM Level 0
, ,
Function onunload
onunload Window , ,
,
.
, Java
Script, onunload
<body> <frameset>.
onunload
.
onunload() ,
. ,
,
(, Window.confirm()
Window.prompt()) onunload.
Window.onload; 17
Window.open()
Window.open()
923
JavaScript 1.0
window.open(url, , , )
url
, URL ,
. ,
.
, .
target HTML <a> <form>.
, open() ,
. .
, ,
.
. ,
.
, , URL
, ,
. true,
. :
.
Window, ,
, .
open() .
, .
, URL url,
. JavaScript ,
, .
, open()
. , URL
url, , ,
, (
). url , open()
.
.
.
target <a> <form> HTML
.
924
Window.open()
Window.open()
, ,
URL .
true, URL .
false , URL
.
, Location.re
place().
Window.open() Document.open()
. open()
Window.open(). , HTML,
open() Document.open(),
Window.open() .
,
.
, . ,
, , ,
.
. :
[=]
yes no.
: ,
yes, no. width height
, .
:
height
.
left
X .
location
URL .
menubar
.
resizable
no, ,
. (
.) :
resizeable e.
scrollbars
,
.
Window.print()
925
status
.
toolbar
, .
top
Y .
width
.
.
Location.replace(), Window.close(), closed opener Window
Window.print()
JavaScript 1.5
window.print()
print() ,
. ,
.
Window.prompt()
JavaScript 1.0
window.prompt(, _)
( HTML) ,
. .
_
, . prompt()
, ("").
, , , ,
null, .
prompt() ,
OK .
,
.
926
Window.removeEventListener()
, prompt() null.
OK, prompt() ,
.
prompt() ,
,
, OK .
, ,
JavaScript ,
,
.
Window.alert(), Window.confirm()
Window.removeEventListener()
. Element.removeEventListener()
Window.resizeBy()
JavaScript 1.2
window.resizeBy(dw, dh)
dw
, .
dh
, .
resizeBy() window ,
dh dw. ,
, Window.resizeTo().
Window.resizeTo()
JavaScript 1.2
window.resizeTo(, )
resizeTo() window ,
.
.
,
. ,
927
Window.scrollBy()
, ,
, .
Window.scrollBy()
JavaScript 1.2
window.scrollBy(dx, dy)
dx
, .
dy
, .
scrollBy() , ,
, dx dy.
Window.scrollTo()
JavaScript 1.2
window.scrollTo(x, y)
X,
.
Y,
.
scrollTo() , window, ,
, x y, ,
.
Window.setInterval()
JavaScript 1.2
window.setInterval(, )
JavaScript JavaScript,
. ,
. IE 4 ( )
.
, .
928
Window.setTimeout()
, Window.clearInterval()
.
Window.clearInterval(), Window.setTimeout()
Window.setTimeout()
JavaScript 1.0
window.setTimeout(, )
JavaScript JavaScript,
. ,
,
. IE 4
.
JavaScript
.
( ),
clearTimeout() .
929
Window.status
Window.clearTimeout(), Window.setInterval()
Window.status
JavaScript 1.0
String status
status ; ,
. ,
, ,
. , status, ,
,
, defaultStatus.
.
,
.
Window.defaultStatus
XMLHttpRequest
HTTP#
ObjectXMLHttpRequest
new XMLHttpRequest()
// , IE 5 IE 6
new ActiveXObject("Msxml2.XMLHTTP")
// IE
new ActiveXObject("Microsoft.XMLHTTP") // IE
Uninitialized . XMLHttpRequest
abort()
Open
open() , send()
.
Sent
send() HTTP .
930
XMLHttpRequest
Receiving
.
,
Loaded
HTTP
readyState ,
abort() open(). ,
, onreadystatechange.
readonly String responseText
( ), ,
, . ready
State 3, ,
. readyState 4,
.
, ,
, UTF8.
readonly Document responseXML
, XML
Document. null,
:
readyState 4;
ContentType "text/xml", "application/
xml" , +xml,
, XML;
XML,
.
readonly short status
HTTP , , , 200
404 . ,
readyState 3, .
readonly String satusText
, HTTP .
status 200, "OK",
404 "Not Found". status,
, readyState 3,
.
abort()
,
.
getAllResponseHeaders()
HTTP .
getResponseHeader()
HTTP .
XMLHttpRequest
931
open()
HTTP, URL, HTTP,
.
send()
HTTP ,
open(), ,
.
setRequestHeader()
HTTP ,
.
onreadystatechange
, ,
readyState. 3
readyState.
XMLHttpRequest JavaScript
HTTP (
XML). XMLHttpRequest 20,
.
XMLHttpRequest
. ,
, XMLHttpRequest. Internet Explorer
ActiveXObject(),
.
XMLHttpRequest :
1. open(), URL
( GET POST). , open()
.
2. , onreadystate
change ,
.
3. setRequestHeader(),
.
4. send() .
POST,
. , send()
,
readyState 4.
onreadystatechange , readyState
4 ( 3).
5. send()
readyState 4 ,
, .
status, , .
932
XMLHttpRequest.abort()
getResponseHeader() getesponseHeaders()
responseText responseXML
.
XMLHttpRequest
, W3C .
. XMLHttpRequest
,
. , null,
, readyState
3, .
20
XMLHttpRequest.abort()
HTTP#
void abort()
XMLHttpRequest ,
0 readyState,
. , ,
.
XMLHttpRequest.getAllResponseHeaders()
HTTP#
String getAllResponseHeaders()
readyState 3, null.
HTTP (
), .
\r\n.
XMLHttpRequest.getResponseHeader()
HTTP#
String getResponseHeader()
HTTP , .
,
, .
XMLHttpRequest.onreadystatechange
933
HTTP ,
readyState 3.
,
.
XMLHttpRequest.onreadystatechange
, readyState
Function onreadystatechange
, ,
readyState. (
) , readyState 3,
.
onreadystatechange readyState XMLHttpRe
quest, , 4.
responseText responseXML.
, .
,
XMLHttpRequest, . ,
,
.
XMLHttpRequest DOM
addEventListener() onreadystatechange. (.,
, Event.addEventListener().) IE
DOM
,
onreadystatechange.
XMLHttpRequest.open()
HTTP#
void open(String ,
String url,
boolean ,
String , String )
HTTP, .
GET, POST HEAD.
.
934
XMLHttpRequest.send()
url
URL, .
(. 13.8.2) ,
URL ,
. URL
URL .
: .
false,
send() , .
true ,
onreadystatechange.
,
URL
, .
, ,
URL.
send(). readyState 1,
, ,
responseText, responseXML, status statusText ,
. , readyState
0 ( XMLHttpRequest
abort()), , readyState 4 (
). open() .
open() ,
send() XMLHttpRequest.
,
.
XMLHttpRequest.send(); 20
XMLHttpRequest.send()
HTTP#
void send(Object )
open() HTTP
POST PUT, ,
Document , , null.
null.
( .)
XMLHttpRequest.setRequestHeader()
935
HTTP.
open() , , readyState 1,
send() .
HTTP, :
HTTP, URL (
), open();
,
setRequestHeader();
, .
, send() ready
State 2 onreadystatechange.
open()
false, ,
readyState 4 .
, true
, send() ,
, .
, send()
.
HTTP , send()
readyState 3 onreadystatechange.
, send()
onreadystatechange 3
. ,
, send()
readyState 4 .
XMLHttpRequest.open(); 20
XMLHttpRequest.setRequestHeader()
HTTP#
. ,
, .
.
.
setRequestHeader() HTTP,
, send().
936
XMLSerializer
, readyState 1, . .
open(), send().
,
,
.
open() , XMLHttpRequest
Authorization.
setRequestHeader(). ,
cookies, URL, open(),
Cookie Cookie2 .
setRequestHeaders() cookie.
, XMLHttpRequest
UserAgent. ,
, .
XMLHttpRequest
HTTP
. , ,
(proxy):
Host
Connection
KeepAlive
AcceptCharset
AcceptEncoding
IfModifiedSince
IfNoneMatch
IfRange
Range
XMLHttpRequest.getResponseHeader()
XMLSerializer
XML#
ObjectXMLSerializer
new XMLSerializer()
serializeToString()
.
XMLSerializer , , XML
Node XML. XMLSerial
izer, ,
serializeToString():
var text = (new XMLSerializer()).serializeToString();
XMLSerializer.serializeToString()
937
DOMParser, Node; 21
XMLSerializer.serializeToString()
XML#
String serializeToString(Node )
XML, .
Document .
XML,
.
XPathExpression
XPath#
evaluate()
.
XPathExpression Document.createExpression()
XPath.
evaluate(). ,
Document.evaluate(),
.
Internet Explorer XPathExpression. ,
IE, Node.selectNodes()
Node.selectSingleNode().
.
Document.createExpression(), Document.evaluate(), Node.selectNodes(), Node.selectSingle
Node(); 21
XPathExpression.evaluate()
XPath#
XPathResult evaluate(Node ,
short ,
XPathResult )
938
XPathResult
( ), .
.
, XPathResult.
XPathResult, ,
null, , evaluate()
XPathResult.
XPathResult, .
,
null.
XPathExpression
XPathResult.
XPathResult.
XPathResult
XPath#
,
XPath. resultType
XPathResult , .
Document.evaluate() XPathEx
pression.evaluate(), .
:
ANY_TYPE
Document.evaluate() XPathExpression.evaluate(),
, .
resultType .
NUMBER_TYPE
numberValue.
STRING_TYPE
stringValue.
BOOLEAN_TYPE
booleanValue.
UNORDERED_NODE_ITERATOR_TYPE
,
iterate
XPathResult
939
Next(), null.
.
ORDERED_NODE_ITERATOR_TYPE
, ,
.
iterateNext(),
null.
.
UNORDERED_NODE_SNAPSHOT_TYPE
.
snapshotLength , snapshotItem()
.
.
(snapshot), ,
.
ORDERED_NODE_SNAPSHOT_TYPE
,
UNDERED_NODE_SNAPSHOT_TYPE, ,
.
ANY_UNODERED_NODE_TYPE
singleNodeValue , ,
null, , .
, singleNodeValue
.
FIRST_ODERED_NODE_TYPE
singleNodeValue
null, .
resultType. ,
resultType,
.
readonly boolean booleanValue
, resultType BOOLEAN_TYPE.
readonly boolean invalidIteratorState
true, resultType ITERATOR_TYPE
, , . .
.
readonly float numberValue
, resultType NUMBER_TYPE.
readonly short resultType
XPath.
.
.
940
XPathResult.iterateNext()
iterateNext()
. ,
resultType UNORDERED_NODE_ITERATOR_TYPE ORDERED_NODE_
ITERATOR_TYPE.
snapshotItem()
.
, resultType UNORDERED_
NODE_SNAPSHOT_TYPE ORDERED_NODE_ SNAPSHOT_TYPE.
XPathResult XPath.
Document.evaluate() XPathExpression.evaluate().
XPath , , ,
. XPath
,
XPath.
XPathResult,
resultType. ,
.
,
resultType, .
Internet Explorer XPathResult. XPath
IE Node.selectNodes() Node.selectSingleNode().
Document.evaluate(), XPathExpression.evaluate()
XPathResult.iterateNext()
, XPath#
Node iterateNext()
throws DOMException
, , null,
.
XPathResult.snapshotItem()
941
,
, XPathResult. ,
, resultType , UNORDERED_NODE_ITERA
TOR_TYPE ORDERED_NODE_ITERATOR_TYPE.
iterateNext() , ,
null, . ,
resultType UNORDERED_NODE_ITERATOR_TYPE OR
DERED_NODE_ITERATOR_TYPE.
(ORDERED), .
.
invalidIteratorState true, ,
, .
XPathResult.snapshotItem()
, XPath#
Node snapshotItem()
null, snapshot
Length.
, resultType ,
UNORDERED_NODE_SNAPSHOT_TYPE ORDERED_NODE_SNAPSHOT_TYPE.
XSLTProcessor
XML#
XSLT
new XSLTProcessor()
clearParameters()
.
getParameter()
.
importStyleSheet()
XSLT.
942
XSLTProcessor.clearParameters()
removeParameter()
.
reset()
XSLTProcessor ,
.
setParameter()
.
transformToDocument()
, importStylesheet(), ,
setParameter().
Document.
transformToFragment()
,
DocumentFragment.
XSLTProcessor XML
XSLT. XSLTProcessor,
importStylesheet() .
, setParameter(). ,
transformToDocument() trans
formToFragment().
Internet Explorer XSLT, XSLTProcessor.
Node.transformNode() Node.transformNodeToObject(),
IE, .
, XSLT
21.
Node.transformNode(), Node.transformNodeToObject(); 21
XSLTProcessor.clearParameters()
void clearParameters()
,
setParameter(). ,
, .
XSLTProcessor.getParameter()
XSLTProcessor.importStylesheet()
943
URI
.
.
null, .
XSLTProcessor.importStylesheet()
XSLT
void importStylesheet(Node )
XSLT, .
Document, <xsl:stylesheet>
<xsl:transform>.
importStylesheet() XSLT,
transformToDocument() transformToFragment().
XSLTProcessor.removeParameter()
URI
.
removeParameter() ,
setParameter().
,
.
XSLTProcessor.reset()
XSLTProcessor ,
void reset()
944
XSLTProcessor.setParameter()
XSLTProcessor ,
. XSLTPro
cessor .
XSLTProcessor.setParameter()
URI
.
XSLTProcessor.transformToDocument()
Document transformToDocument(Node )
.
Document, .
XSLT
Document.
XSLT, importStylesheet(), ,
setParameter().
XSLTProcessor.transformToFragment()
945
XSLTProcessor.transformToFragment()
DocumentFragment
Document transformToFragment(Node ,
Document )
, DocumentFragment.
ownerDocument DocumentFragment
.
DocumentFragment, .
XSLT
DocumentFragment.
XSLT, importStylesheet(), ,
setParameter().
, .
& (), 79
&& ( ), , 79
&=, , 79
, 79
' (), ,
, 44
: (), , 109
(),
, 217
@ ( at)
XPath, 532
CSS, 399
> (), , 79, 86
>= ( ) , 79,
86
>> (
) , 79
>>=, , 79
>>> (
) , 79
>>>=, , 79
, 60
< () , 79, 86
<!, ,
264
<= ( ) , 79,
86
, 60
_ ()
, 36
, 142
, 206
! ( )
!= () , 79, 85
!== () , 79, 85
! important,
, 368
, 78
$ ( )
, 36, 161
, 215, 222
, 709
% ( )
%=, , 79
, 79, 82
" ( )
, 220
, 43
' ( )
, 220
, 43
() ( )
, 244
if, 101
, 52, 139
, 219, 221
, 78, 113
, 81
* ()
*=, , 79
CSS,
, 361
, 218
, 42, 79, 82
, 81
+ ()
++ , 78, 82, 99
, 35
+=, , 79
, 81
CSS,
, 361
, 218
, 45, 59,
79, 81, 88
, 42, 79, 81
, 81
, 60
, 80
( ), 78
()
, , 78, 83, 99
, 35
=, , 79
Infinity, 42
, 42, 79, 82
, 78, 82
, () , 79, 97
. (), , 52, 78, 97, 125
XPath, 532
, 217
, 123
/ ()
/* */, , 35
URL JavaScript, 266
//
, 35
XPath, 532
/=, , 79
, 56
,
214
, 42, 79, 82
; ( )
do//while, 107
, 119
, 99
= ( )
== () , 79, 83
null unde
fined, 55
,
85
=== () , 79, 83
case,
, 105
, 84
, 79
? ( )
?!
, 222
947
?: () , 79, 94
?=
, 222
URL, 289
, 218
(CSS), 362
[] ( )
, 52, 125
JavaArray, 244
, 53, 130
, 133
, 216
CSS, 361
, 78
\ ( )
\n (
), 221
, 215
, 43
, 44
^ ( )
^=, , 79
, 222
, 79
, 217
{} ( )
, 53
, 100
, 113
try/catch/finally, 116
, 218
CSS, 362
| ( )
|= , 79
|| CSS, 361
|| , 79
, 79
, 219, 221
948
~ ()
,
78
, 92
32 , 40, 91
64
(), 40
A
<a>, , 723, 850
onclick, , 322
onmouseover, , 405
target, , 307
href, 267
Link
, 850
abort(), (XMLHttpRequest), 508
accept, (Input), 835
accessKey, (Input), 836
action, , URL javascript:
, 267
action, , 454
ActionScript, , 22, 286,
576, 597
canvas.as, 576
ExternalInterface, , 605
SharedObject, , 483
JavaScript
fscommand(), 600
JavaScript
(), 601
JavaScript
, 599
Flash, 492
(mtasc), 598
ActiveXObject(), , 496
addCallback(), (ExternalInterface),
605
addEventListener(), , 416
this, 418
addRule(), , 400
Ajax, 509
URL, 514
, 514
, , 511
, 515
, 513
,
514
, 514
RPC, 510
AJAXSLT, 531
alert(), , 24, 117, 259, 302, 913
, 285
, 303
, 29
align, (Input), 836
all[], , 358
Document, , 276
HTMLDocument, , 816
alt, (Input), 836
altKey, , 441, 848, 857
Event, (IE), 426
MouseEvent, , 424
Anchor, , 723
Anchor. focus(), , 724
anchors[], , Anchor, 724
animateCSS(), , 394
API , 398
API
CSSDrawing, , 558
Flash, 547
appCodeName, (Navigator), 295,
859
appendChild(), (Node), 325, 343
appendData(), , 341
Applet, , 724
applets[], , 590
application/xjavascript, MIME, 261
apply(), (Function), 153, 171
appName, (Navigator), 295, 859
<area>, , Link
, 850
Arguments, , 613
callee, , 145
length, , 145
arguments[], (Arguments), 144,
613
Array, , 615
concat(), , 135
join(), , 133
pop(), , 136
push(), , 136
reverse(), , 134
shift(), , 136
949
slice(), , 135
sort(), , 134, 181
splice(), , 135
toLocaleString(), , 128, 137
toString(), , 137
unshift(), , 136
, 133 137
Array(), , 54
, 130
ASCII, , 440
ASCII, , 33
attachEvent(), , 427
this, 429
Attr, , 325, 725
attributes[] , 326
Node, , 861
availHeight, (Screen), 294
availWidth, (Screen), 294
borderbottom, , 379
borderleft, , 555
borderleftwidth, , 379
bordertop, , 555
bordertopwidth, , 379
bottom, , 370, 381
break,
switch, 104
, 35
bubbles, (Event), 422, 797
button, , 857
Event, (IE), 425
MouseEvent, , 423
button, , 456, 462
<button>,
onclick, , 407
, 463
\B () , 222
\b ( )
, 222
\b () , 217
back(),
History, , 291, 311
Window, , 291
background, , 371, 382
backgroundattachment, , 382
backgroundcolor, , 382
backgroundcolor, , 555
backgroundimage, , 382
backgroundposition, , 382
backgroundrepeat, , 382
bgColor, (Document), 317, 318
bind(), , 444
Bindings, , 230
Java
JavaScript, 234
blur(),
HTMLInputElement, , 327
Window, , 299, 915
Link, , 852
body, , 336, 525, 817
<body>,
onload, , 265, 269
, 292
, 268
Boolean, , 624
border, , 371, 379, 548
border, , 555
C/C++
char, , 43
JavaScript
C, 28
switch, 105
++, 173
,
JavaScript, 35
, 125
call(), (ExternalInterface), 605
callee, (Arguments), 145, 614
cancelable, (Event), 423, 797
cancelBubble, (IE Event), 428
Canvas, , 726
<canvas>, , 274, 547, 572
, 574
CanvasGradient, , 727
CanvasPattern, , 728
CanvasRenderingContext2D, , 729
caption, , 896
case, ( switch), 104, 109
catch, (try/catch/finally), 116
CDATASection, , 749, 760
cellIndex, , 900
cells, , 900
CERT Advisory,
, 285
char, (Java)
JavaScript
, 247
CharacterData, , 341, 749
950
charAt(), , 46
charCode, , 441, 849
check(), , 152
checkbox, , 456, 463
name, , 460
checked, (Input), 836
, 463
childNodes[] (Node), 325, 334,
357, 861
children[], , 357
class, (HTML), 328, 396
className, , 327, 396, 823
HTMLElement, , 328
, 396
clearInterval() (Window), 288, 915
clearTimeout() (Window), 288, 507,
916
clientInformation, , 294
clientX clientY, , 435
Event, (IE), 426
MouseEvent, , 424
clip, , 370, 383
close(),
Document, , 298
write(), 317
Window, , 298, 300, 916
closed, (Window), 299, 909
collapsed, , 878
color, , 382
Comment, , 325, 753
commonAncestorContainer, , 878
Comparable, , 193
compare(), , 181
compareTo(), , 180
complete, (Image), 554
concat(), (Array), 135
confirm(), , 302
, 302
constructor, , 167, 687
contentDocument, (Form), 811
ContentScriptType, (HTTP),
261
ContentType, (HTTP), 506
continue, , , 35
confirm() , 916
cookie,
Document, , 317, 472, 473
HTMLDocument, , 817, 819
Cookie(), , 477
Cookie, (), 477
cookieEnabled, (Navigator), 859
cookies, 472
Cookie, (), 477
domain, , 474
Internet Explorer, 481
path, , 473
secure, , 474
, 481
Flash SharedOb
ject, 483
userData,
481
(), 485
, 473
, 473
HTTP, 498
, 472
(), 475
, 475
,
, 476
, 476
, 476
countTags(), , 334
createDocument(), , 519
createDocumentFragment(), (Docu
ment), 343
createElement(), (Document), 343
createElementNS(), , 568
createEvent(), , 450
createEventObject(), , 450
createExpression(), (Document),
531, 536
createNamespace(), (Module), 208
createTextNode(), (Document), 343
CSS (Cascading Style Sheets
), 360
behavior, ,
, 482
DHTML, 370
position, , 370
CSS
, 379
, 376
, 378
, 384
951
, (
), 373
, 370
,
zindex, 378
,
, 382
, 383
DHTML, 391
, 361
,
362
, 368
, 397
CSS
(), 389
, 395
,
386
, 398
(), 368
, 368
, 366
VML,
, 569
CSS, 396
, 397
, 388
, 366
, 273
, 387
,
, 368
CSS2Properties, , 386, 753
cssText, , 399
CSS, 387
getComputedStyle() (Window), 395
CSSDrawing, , 558
CSSRule, , 399, 755
cssRules[], , 399
CSSStyleSheet, , 399, 756
deleteRule(), , 400
insertRule(), , 400
cssText, , 399, 753
ctrlKey, , 424, 441, 849, 857
D
\D (, ASCII) ,
, 217
\d, , ASCII, 217
data,
CharacterData, , 749
ProcessingInstruction, , 877
SharedObject, , 484
Date, , 39, 56, 626
toLocaleString(), , 128
+, , 61
,
, 64
, 627
, 628
Date(), , 56
decodeURI(), , 646
decodeURIComponent(), , 475,
476, 647
default: ( switch), 104,
109
defaultChecked (Input), 836
checkbox, , 463
radio, , 463
defaultSelected, , 874
defaultStatus, (Window), 304,
910, 917
defaultValue, (Input), 836
Textarea, , 905
defer, (<script>), 262, 268, 316
delete, , 78, 99, 545
C++ JavaScript, 96
, 125
, 131
deleteData(), , 341
deleteRule(), (CSSStyleSheet), 400
description,
MimeType, , 856
Plugin, , 876
detachEvent(), , 427, 761, 918
detail, (UIEvent), 423, 908
DHTML (Dynamic HTML), 360
CSS, 370
,
371
952
CSS
(), 389
, 378
,
( ), 373, 376
,
zindex, 378
, 395
, 398
, 397
DOM,
, 276
dir, , 327, 823
disabled,
Input, , 836
Option, , 874
dispatchEvent(), , 450
display, , 370, 378
displayNextFrame(), , 394
distance(), , 140
<div>,
onmousedown, , 440
CSS, 390
do/while,
continue, , 111
<!DOCTYPE>, , 381
doctype, , 759
Document, , 253, 314, 325, 327, 759
all[], , 276
IE_4 DOM, 358
applets[], , 590
children[], (IE_4 DOM), 357
createAttribute(), , 760
createAttributeNS(), , 760
createCDATASection(), , 760
createComment(), , 760
createDocumentFragment(), ,
343, 760
createElement(), , 343, 760
createElementNS(), , 568, 760
createEvent(), , 450, 760
createEventObject(), , 450
createExpression(), , 760
createProcessingInstruction(), ,
760
createRange(), , 760
createTextNode(), , 343, 760
domain, , 282
evaluate(), , 761
forms[], , 454, 460
getElementById(), , 276, 338,
366, 590, 761
getElementsByTagName(), ,
336, 761
getElementsByTagNameNS(), ,
761
getSelection(), , 357
implementation, , 329
importNode(), , 761
loadXML(), , 522, 761, 772
location, , 291
open(), , 413
removeEventListener(), , 761
styleSheets[], , 399
write(), , 24, 259, 262, 268, 316
onload, , 269
, 320
, 760
, 321
, 759
(), 322
document, (Window), 253, 314,
910
documentElement, , 325, 336, 759
XML, 525
DocumentFragment, , 325, 342, 773
DocumentType, , 773
DOM (Document Object Model
), 253
API (CSS2Properties), 386
Common DOM API, 596
IE 4, 357
W3C DOM, 323
XML API, 524
,
351
,
343
, ,
332
, 339, 359
, 334, 357
HTTP, 506
, 335,
357
, 356
, 323
,
, 276
, 314
,
329
, 325
, 328
DOM Scripting Task Force, JavaScript
Manifesto, 257
DOMAccessor, , 596
DOMAction, , 596
domain, (cookies), 474, 475
domain,
Document, , 282, 317
HTMLDocument, , 817, 820
DOMException, , 774
DOMImplementation, , 329, 776
DOMParser, , 522, 780
DOMService, , 596
E
E, (Math, ), 672
e E,
, 41
E4X (EcmaScript XML), 22, 543
, 545
XML, 545
XML, 545
, 545
, 545
ECMAScript, , 22
v1, Unicode
, 43
v3
,
, 36
(throw)
Error, 116
, 37
, 33
, 36
Perl RegExp,
, 223
, 54
, 53
, 43
Element, , 325, 327
childNodes[], , 357
getElementsByName(), , 338
XML HTML, 525
953
,
349
, 326
Element, , 781
elements[], (Form), 254, 454,
807, 809
fieldset, , 467
else, , if, 101
else if, , 102
<embed>, , 598
enabledPlugin, , 856
encodeFormData(), (HTTP), 504
encodeURI(), , 647
encodeURIComponent(), , 475,
476, 648
encoding, , 454
endContainer, , 878
endOffset, , 878
endsWith(), (String), 170
equals(), , 180
Error, , 40, 649
escape(), , 475, 651
eval(), , 161, 230, 652
JSObject, , 594
ScriptEngine, , 230
JSON,
507
EvalError, , 653
evaluate(), (Document), 531, 536
event, (<script>), 264
Event, , 419, 420, 797
currentTarget, , 418
initEvent(), , 450
IE, 797
, 799
, 797
Event, (IE), 425
, 427
event,
Window , 427
EventListener, , 419
eventPhase, (Event), 422, 797
Events API, (DOM), 419
exec(), (RegExp), 226
expandTemplates(), , 538
expires, (cookie), 473
, 476
Extensible Stylesheet Language,
, 528
ExternalInterface, , 576, 605, 801
954
F
factorial(), , 117, 140
<fieldset>, , 467
file, , 456, 464
filename, (Plugin, ), 876
FileUpload, ,
, 281
filter, (IE), 383
filter(), (Array), 137
finally, (try/catch/finally), 116
fireEvent(), , 450
Firefox,
availLeft availTop, (Screen,
), 294
<canvas>,
, 274
document.all[], , 277
keyCode charCode, , 441
opacity, , 383
selectionStart selectionEnd,
, 357
,
137
Navigator, 297
, 272
,
, 419
, 273
JavaScript, 305
SVG, 563
, 282
, , 274
firstChild, (Node), 325, 332,
335, 861
Flash, 576, 588
API , 547
PObject, , 485
SharedObject, ,
483
8, 605
, 597
JavaScript Flash, 600
, 601
, 485
ActionScript, 492
, 578
, , 598
, 485
, 576
Flash, 599
FlashPlayer, , 803
float, , 387
flush(), (SharedObject), 484
focus(),
HTMLInputElement, , 327
Link, , 852
Window, , 299, 918
, 300
for, (<script>), 264
for/each/in, , 545
for/in, , 30, 108
continue, 111
var, 68
, 126
,
124, 689
, 662
forEach(), (Array), 137
Form, , 254, 321, 454, 460, 807
onsubmit, , 410
onsubmit, , 322
, 410
form, , 461
Input, , 836
Option, , 874
Select, , 891
Textarea, , 905
<form>, , 807
name, , 321, 460
onsubmit, , 322, 407
target, , 307
, 321
forms[],
Document, , 254
HTMLDocument, , 327, 817
forward(),
History, , 291, 311
Window, , 291
Frame, , 811
<frame>, , 307
name, , 307
src, , 494
frames[], (Window), 253, 307,
910
<frameset>, , 307
fromCharCode(), (String), 426
fromElement, toElement,
(IE Event), 426
955
fscommand(), , 600, 601
function, , 139
function, , 310
Function(), , 51, 163
Function, , 654
apply(), , 171
G
g, ( ), 696, 698
g, ( ), 223,
225, 228
GET, (HTTP), 497
XMLHttpRequest, 502
<iframe>, 516
get(), (HTTP), 508
getAllResponseHeaders(), , 499
getArgs(), , 289
getAttribute(),
Element, , 326
getAttributeNode(), , 326, 725
getClass(), , 240, 659
getComputedStyle(), (Window),
395, 918
getElementById(), (HTMLDocu
ment), 338, 547
Document, , 366
HTML XML, 525
getElementsByName(),
(HTMLDocument), 338
getElementsByTagName(), , 547
Document, , 336
Element, , 337
getFirstChild(), , 332
getHeaders(), (HTTP), 503
getNode() getNodes(), , 538
getResponse(), (HTTP), 504, 507,
508
getResponseHeader(), , 499
getSelection(), , 357
getText(), (HTTP), 502, 508
getTextWithScript(), (HTTP), 517
GetVariable(), , 599
getWindow(), , 593
getXML(), (HTTP), 502
global, (RegExp), 228, 698
go(), (History), 291
Google AJAXSLT, 531
Google Maps, , 515
H
handleEvent(), , 419
hasFeature(), , 329
c, 331
,
, 329
hash,
Link, , 850
Location, , 300
hasOwnProperty(), (Object), 128,
168
HEAD, (HTTP), 497
XMLHttpRequest, 503
<head>, , , 268
height, , 370, 381
height,
Image, , 52
Screen, , 294
hidden, , 456
History, , 289, 311, 812
back() forward(), , 291
history, (Window), 291, 910
host,
Link, , 850
Location, , 289
hostname, (Link, ), 850
href,
<a>, , 851
, 267
href,
Link, , 850
Location, , 289, 311
HTML
<canvas>, , 547, 572
checked, , 463
DOM API, 326
DocumentFragment, , 342
, 343
, 339
, 335
,
356
,
328
XML, 526
FileUpload, ,
, 281
956
<frameset>, <frame> <iframe>,
, 307
mayscript, , 595
multiple, , 465
name, , 307, 460
style, , CSS
, 365
visibility display, , 378
VML , 570
XML HTML, 524
, 404
, 370
JavaScript , 24, 258
<script>, , 258
<script>, 264
, 263
, 259
Flash
, 598
Canvas.swf, 578
, 369
, 324
String, 702
, 264, 321
,
IE 6
, 381
, 260
XML, 522
HTMLElement, 327
, 314
, 273
CSS,
, 366
IE, 277
HTMLBodyElement, , 327
HTMLCollection, , 814
HTMLDocument , 327, 816
body, , 336
children[], , 357
HTMLElement, , 327, 525, 823
HTML
, 826, 827, 828
innerHTML, , 351
style, , 389
, 824
HTML, 825
HTMLEvents, , 420, 422
HTMLFormElement, , 327
HTMLInputElement, , 327
HTMLUListElement, , 327
HTTP, 494
Ajax , 509
, 513
, 511
, 514
ContentScriptType, , 261
USERAGENT, , 295, 859
, 501
<script>, 516
XMLHttpRequest, 282
<img>, <frame> <script>, 494
,
, 499
XMLHttpRequest, 495
, 499
, 497
,
, 274
, 498
, 502
XMLHttpRequest,
496
HTTPS, 474
I
i, (
), 696, 698
i, ( ), 223,
228
id, ,
, 327, 366
id, , 327, 823
if, , 101
else, 101
, 102
if/else ,
, 49
IFrame, , 832
<iframe>, , 307
src, , 495
HTTP GET, 516
,
514
ignoreCase, (RegExp), 228, 698
Image, , 547, 833
, 321
, 834
onload, 552
, 554, 833
src, 548
, 52
HTML, 833
ImageLoop, , 552
images[], (Document), 547
<img>, , 834
name, , 321, 460, 547
src, , 494
src width, , 326
implementation, (Document),
329, 759
@import, (CSS), 367
importClass(), , 241
importPackage(), , 241
importSymbols(), (Module), 208
in, , 79, 87
, 124
index,
Array, , 225
Option, , 874
indexOf(),
Array, , 137
String, , 46, 476
Infinity
, 43
, 58
Infinity, 42
Infinity, , 663
initEvent(), , 450
initUIEvent(), , 450
innerHeight, innerWidth,
(Window), 910
innerHTML, , 263, 505, 823
Input, , 835
name, , 840
, 837
, 837
, 835
, 838
input, , 225
<input>, , 841
onclick, , 405, 407
<button>, 463
957
, 463
insertBefore(), (Node), 325, 343
insertChildBefore(), , 545
insertData(), , 341
insertRule(), (CSSStyleSheet), 400
instanceof, , 79, 87
Internet Explorer (IE)
clientInformation, , 294
currentStyle, ,
, 395
document.all[], , 276
document.selection, , 357
DOM, 315
filter, , 383
Function.apply(), , 171
rules[], , 399
5 6, XMLHttpRequest, 496,
516
4 5.5, width
height, 381
6, CSS
, 381
, 292
Navigator, 297
, 272
, 424
Event, , 425
,
427
Event, 797
keyCode, , 441
keypress, , 441
, 428
(), 437
, 428
, 427
, 273
XML, 522
, 162
XML, 519
DOM, 23, 329,
331
, 274
isFinite(), , 42, 663
isNaN(), , 42, 84, 663
ISO Latin1, , 33
isPrototypeOf(), (Object), 129
958
J
Java, , 20, 664
API , 547
char, , 43
JavaScript
, 593
,
JSObject, 594
Java JavaScript, 595
, 581
canvas
, 581
JavaScript, 581
, 584
JavaScript (Rhino), 28
, 173
JavaScript, 172
, 229
Common DOM API, 596
JavaArray, , 244
JavaScript, 229
JavaScript, 236
,
JavaScript, 232
, 243
, 245
JavaScript, 230
Java
Script, 245
, 125
java.lang, ,
importPackage(), 242
java.lang.reflect, ,
Java, 245
Java2D API, 581
JavaArray, , 244, 664
JavaClass, , 240, 665
, 244
, 248
javaEnabled(), , 860
JavaObject, , 242, 596, 667
, 244
, 248
JavaPackage, , 239, 668
JavaScript
, 280
, 283
,
280
,
281
URL, 266
, 267
, 279
,
37
, 28
, 43
, 33
, 609
, 723
,
45
JavaScript API XSLT, 531
JavaScript Archive Network (JSAN), 198
JavaScript Object Notation (JSON),
JavaScript, 506
javascript:, , 29, 258, 266
href, 269
javax.script, , 230
JavaScript, 236
, 234
join(), (Array), 133
.js, 259
JScript, , 278
JSObject, , 593, 668, 844
, Common
DOM API, 596
, JSObject, 594
Java
JavaScript, 595
JSON (JavaScript Object Notation
JavaScript), 506
K
keyCode, (IE Event), 426, 441,
849
keydown, , 440
KeyEvent, , 848
KeyListener, (Java),
JavaScript, 236
keypress, , 440
keyup, , 440
959
L
L ( )
, 81
label, , 874
<label>, , 467
for, , 328
lang, , 327, 823
language, (<script>), 261
lastChild, , 335, 861
Node, , 325
lastIndex,
RegExp, , 228, 698
String, , , 227
lastIndexOf(), (Array), 137
lastModified,
Document, , 318
HTMLDocument, , 817
Latin1, ,
,
,
44 45
Layer, , 849
left, , 370, 381
length, , 872, 891
Arguments, , 145, 613, 749,
808
arguments[], , 144
Array, , 132
HTMLFormElement, , 328
Plugin, , 876
String, , 706
, 130, 138
, 132
,
132
, 45
, 152
length, (CSS), 361
Link, , 849
onclick, , 410
onclick, , 322
, 851
, URL, 849
, HTML
, 850
<link>,
disabled, , 397
, 367
CSS
HTML, 366
listanchors(), , 322
LiveConnect, 237
JavaPackage, , 239
, 245
Java, 245
Java
JavaScript, 239,
592
load(), (XML), 521
loadXML(), (Document), 522
localeCompare(), (String), 87
localName, (Node), 861
Location, , 253, 289, 853
hash, , 300
replace(), , 300
, 854
, 853
location, , 289, 327
Document, , 291, 318
Window, , 253, 410, 910
HTTP,
494
URL, 290
M
m, ( ), 696
m, ( ), 223,
228
makeBarChar(), , 556
makeCanvas(), , 568
makeDataURL(), , 568
makeObjectTag(), , 568
Map, (Java), 232
map(), (Array), 137
margin, , 371, 379
match(), (String), 225
Math, , 42, 668
max(), , 154
max(), , 144, 154
Math, , 154
maxage, (cookie), 473, 476
maxLength, (Input), 836
MAX_VALUE, , 680
mayscript, , 595
message, ( Error), 57
<meta>, , 261
metaKey, , 857
method, , 454
Microsoft
JScript, , 28
Visual Basic Scripting Edition, 260
960
VML (Vector Markup Language
), 547
Netscape, 274
MIME
text/javascript, 261
text/xml, 499
MimeType, , 856
MIN_VALUE, , 680
Module.runInitializationFunctions(),
(Module), 208
mousedown, , 417
MouseEvent, , 420 423, 857
initMouseEvent(), , 450
MouseEvents, (DOM), 420
moveBy(), (Window), 299, 919
moveTo(), (Window), 299, 919
Mozilla
JavaScript API XSLT, 531
JavaScript
, 28, 230
MSXML2.DOMDocument, , 519
mtasc, ActionScript, 598
multiline, (RegExp), 228
multiple, , 465
MutationEvents, , 420
N
\n ( ), 43
name, , 321
checkbox, , 463
<embed>, , 599
<frame>, , 307
<img>, , 547
, 460
name, (Input), 773, 836
Image, , 833
Plugin, , 876
Window, , 910
, 461
namespaceURI, (Node), 861
NaN (notanumber), , 42, 663,
678, 680
isNan(), , 663
, 43
, 57
, 49
0/0, 82
, 87
, 84
Navigator, , 294, 858
navigator, (Window), 294, 910
NEGATIVE_INFINITY, , 681
Netscape
DOM, 314
Microsoft, 274
new Array(), , 96
new, , 56, 78, 95, 165
, 123
String, 59
Java,
241
, 167
newDocument(), (XML), 519
newRequest(), , 496
nextSibling, , 335, 862
Node, , 325
Node, , 327, 860
attributes[], , 326
, 335, 861
NodeList, , 872
nodeName, (Node), 862
nodeType, (Node), 325, 334, 862
nodeValue, (Node), 862
<noscript>, , 263
null, , 55
null, , 39
, 57
Java
JavaScript, 595
, 85
Number, , 678
toLocaleString(), , 128
, 43
, 47
O
Object, , 127, 182, 685
constructor, , 127
hasOwnProperty(), , 128, 168
isPrototypeOf(), , 129
propertyIsEnumerable(), , 128
toLocaleString(), , 128
toString(), , 127
valueOf(), , 128
, 686
Object(), , 59, 183
<object>, , 598
offsetLeft offsetTop,
, 300, 376
offsetParent, , 377
offsetWidth offsetHeight, ,
377
offsetX, offsetY, (IE Event
), 426
onabort, , 554
onblur, , 462
onblur, , 841
onchange, , 265
Select, , 894
, 461
file, 464
Select, , 465
, 464
, 464
onchange, (Input), 842
onchange, , 26
onclick, , 407
onclick,
Link, , 410
Submit, , 410
onclick, , 26, 265, 405
(), 410
, 322
, 464
, 462
, 461
onclick,
HTMLElement, , 828
Input, , 843
Link, , 322, 852
onerror, , 304, 554
onfocus, , 921
, 462
onfocus, (Input), 843
onkeydown, , 440, 465
onkeypress, , 440, 465
onkeyup, , 440, 465
onload, , 265, 268,
269, 538
Image, , 552
Window, , 921
, 272
onload, , 449
onlosecapture, , 429
onmousedown, , 440
onmousedown, , 265
onmouseout, , 265
, 548
961
onmouseout, (Link, ), 853
onmouseover, , 265,
405
true
URL
, 411
, 548
onmouseover, (Link, ), 853
onmouseup, , 265
onreadystatechange,
, 500, 508, 933
onreset, , 454, 455
onresize,
Window, 922
onsubmit, , 407
onsubmit, (Form), 410
onsubmit, , 322, 405,
454
false, 410
onsubmit, (Form), 322, 410
onunload, , 270
Window, , 922
opacity, , 371, 383
open(),
HTTP, 497
Window, , 297, 923
, 266
XMLHttpRequest , 933
write(), 316
opener, (Window), 298, 911
Opera,
, 273
, , 275
<optgroup>, , 466
Option, , 456, 465, 874
, 874
Option(), , 466
<option>, , 320, 875
options[],
Select, , 465, 891, 895
null , 466
outerHeight, outerWidth,
(Window), 911
overflow, , 371, 383
ownerDocument, (Node), 862
962
P
<p>, , 536
Packages, , 592
Packages, , 692
padding, , 371, 379
pageXOffset pageYOffset,
(Window), 424, 911
parent, (Window), 307, 911
parentNode, (Node), 325, 862
parentStyleSheet, , 756
parseFloat(), , 48, 692
parseInt(), , 48, 693
password, , 456, 464
path, (cookie), 473, 475
pathname, (Location), 289
pattern, , 467
pattern, , 215
Perl
,
56, 215
RegExp,
JavaScript, 223
PHP
(jsquoter.php), 517
platform, (Navigator), 295
Plugin, , 876
PObject, (), 485
point, ,
, 53
pop(), (Array), 136
position,
, 371
, 372
POSITIVE_INFINITY, , 681
POST, (HTTP), 497, 504
prefix, (Node), 862
preventDefault(), , 416, 420, 423
previousSibling, , 335, 862
Node, , 325
print(), (Window), 925
print(), , 140
ProcessingInstruction, , 767, 877,
925
prompt(), , 117, 162, 302
, 302
propertyIsEnumerable(), (Object),
128
protocol, (Location), 289
prototype, , 167
, 153
publicId, , 774
push(), (Array), 136
R
R ( )
, 81
radio, , 457, 463
name, , 460
Range, , 878
RangeError, , 694
RangeException, , 889
readOnly, (Input), 836
readyState, (XMLHttpRequest),
500, 929
readyState 3, 501
ReferenceError, , 695
referrer,
Document, , 318
HTMLDocument, , 817
RegExp, , 56, 214, 226, 695
, 226
RegExp(), , 215, 226
registerInitializationFunction(),
(Module), 208
relatedTarget, (MouseEvent),
424, 857
releaseCapture(), , 428
reload(), (Location), 290, 855
remove(), , 477
removeAttribute(),
Element, , 326
removeChild(), (Node), 325
removeEventListener(), , 418, 926
removeRule(), , 400
replace(),
Location, , 290, 855
String, , 224
replaceChild(), (Node), 325, 343
replaceData(), , 341
require(), (Module), 208
required, , 467
Reset, , 454
reset, , 457, 462
reset(), , 454
HTMLFormElement, , 328
resizeBy(), (Window), 299, 926
resizeTo(), (Window), 299, 926
responseText, , 499, 505, 930
responseXML, , 499, 506, 930
returnValue, (IE Event), 426
reverse(), (Array), 134
Rhino, JavaScript, 28, 230
LiveConnect, 237
, 241
, 243
Java, 245
right, , 370, 381
rowIndex, , 901
rows, , 896
TableSection, , 902
rules[], (IE), 399
run(),
DOMAction, , 596
S
\S, Unicode, 217
\s,
, 217
Safari,
<canvas>,
, 274
Mac OS, 273
Navigator, 297
( 2.0), 275
Screen, , 294, 890
screen, (Window), 294, 911
screenLeft, screenTop, screenX, screenY,
(Window), 911
screenX, screenY,
(MouseEvent), 424, 857
<script>, , 258
src, , 259
src, , 494
HTTP, 514
HTTP,
516
document.write(), 316
, 271
, 270
, 268
, 263
, 284
</script>, , 263
ScriptContext, , 232
ScriptEngine, , 230
ScriptException, , 230
963
scrollBy(), (Window), 299, 927
scrollIntoView(), , 300
scrollTo(), (Window), 299, 927
search, (Location), 289
search(), (String), 224
sectionRowIndex, , 901
secure, (cookie), 474, 475
Select, , 456, 466, 891
<select>, , 892
multiple, , 465
onchange, , 265
<option> , 320, 875
selected, , 465, 874
selectedIndex, , 465, 891
selectorText, , 755
self, (Window), 253, 911
send(), (XMLHttpRequest), 498,
500, 934
, 507
setAttribute(),
Element , 326, 342
setCapture(), , 428
setInterval(), (Window), 285, 288,
301, 391, 552, 927
, 304
setRequestHeader(), , 935
setTimeout(), (Window), 288, 311,
392, 451, 507, 928
SetVariable(), , 599, 601
SharedObject, , 483
shift(), (Array), 136
shiftKey, , 441, 849, 857
Event, (IE), 426
MouseEvent, , 424
SimpleBindings, , 232
sin(), , 42
size, (Input), 837
slice(), (Array), 135
SOAP, 540
, 540
sort(), (Array), 134, 150, 181
source, (RegExp), 228, 699
Spidermonkey, Java
Script, 28, 230
LiveConnect, 237
, 242
splice(), (Array), 135
split(), (String), 225, 476
square(), , 51
, 51
964
src,
<script>, , 259
<xml>, , 522
src, (Input), 837
Frame, , 811
Image, , 833
<img>, <frame> <script>, , 494
srcElement, (IE Event), 425
startContainer, , 878
startOffset, , 878
status,
Window, , 303, 911, 929
XMLHttpRequest, , 930
statusText, (XMLHttpRequest),
930
stopPropagation(), , 415, 423
store(), , 477
String, , 59, 700
HTML, 702
, 701
, 170
style, , HTML, 365, 395
style, , 361, 755, 824
HTML, 395
HTMLElement, , 327, 389
<style> </style>, ,
CSS, 366
<style>,
disabled, , 397
styleSheets[], , 760
Submit, , 453, 454
Submit, , onclick , 410
submit, , 457, 462
submit(), (Form, ), 454
substring(), , 476
suffixes, , 856
SVG (Scalable Vector Graphics),
), 286,
546, 562
, 562
, 567
XHTML, 563
SVG.ns, 566
JavaScript, 565
, 563
<svg:path>, , 566
SWF, 493
switch,
break, , 104, 110
case, , 104
default, , 104
SyntaxError, , 716
System, , 592
systemId, , 774
T
tabIndex, (Input), 837
Table, , 896
, 896
,
HTML <table>, 896
<table>, , 896
TableCell, , 900
TableRow, , 900
TableSection, , 902
tagName, , 525, 781
target, (<a> <form>, ),
297, 307
target,
Event, , 422, 797
Form, , 454
ProcessingInstruction. , 877
tBodies, , 896
<tbody>, , 903
<td>, , TableCell,
HTML, 900
test(), (RegExp), 227
Text, , 325
Text, , 326, 904
, 768
text, , 875
Option, , 465
Text, , 457, 464
text(), , 532
textshadow, (CSS), 373
text/javascript, MIME, 261
text/xml, MIME, 499
Textarea, , 905
, 906
, HTML
, 906
textarea, , 457, 464
<textarea>, , 464, 906
onchange, , 265
tFoot, , 896
<tfoot>, , 903
<th>, , TableCell,
HTML, 900
965
tHead, , 896
<thead>, , 903
this, , 95, 151
, 408
, 174
, 175
, 411, 462
addEventListener(), , 418
IE, 428, 785
, 74, 662
timeStamp, (Event), 422, 797
title, , 817, 824
Document, , 318
HTMLElement, , 327
toExponential(), ( Number),
47
toFixed(), ( Number), 47
toLocaleString(),
Array, , 137
Object, , 128
toLowerCase(), (String), 87
top, , 370, 381
top, , 307
Window, , 911
toPrecision(), ( Number), 47
toString(), , 82, 178
Array, , 137
Complex, , 183
Date, , 61
Object, , 127
, 53
, 60
, 47
toUpperCase(), (String), 87
<tr>, , TableRow,
HTML, 901
transform(), , 530
transformNode(), , 530
true false, ,
, 49
try, (try/catch/finally), 116
type, (<script>), 261
type,
Event, , 422, 797
Event, (IE), 425
Input, , 837
MimeType, , 856
Select, , 465, 891
Textarea, , 905
, 456
TypeError, , 717
U
UIEvent, , 420, 422, 423, 908
initUIEvent(), , 450
unbind(), , 444
undefined, , 55
undefined,
Java, 595
undefined, , 718
undefined, , 39, 193
, 57
, 85
unescape(), , 475, 718
Unicode, , 33
keypress, , 426
, 37
, 43
,
,
44
unshift(), (Array), 136
URIError, , 718
URL
Ajax , 514
JavaScript , 266 268
, 267
, 269
HTML, 258
XMLHttpRequest, , 501
location, 290
, 289
URL,
Document, , 318
HTMLDocument, , 817
useMap, (Input), 837
userAgent, (Navigator), 295, 859
userData,
,
483
, 483
, 483
966
V
value, (Input), 837, 875
button, , 463
checkbox, , 464
file, , 464
FileUpload, ,
, 281
Hidden, , 466
Option, , 465
radio, , 464
text, , 464
Textarea, , 905
, 461
valueOf(), , 53, 82, 179
Date, , 61
Object, , 128
, 60
var, , 68, 112
VBScript
JavaScript, 601
, 261
view, (UIEvent), 423, 908
visibility, , 370, 378
VML (Vector Markup Language
), 547, 569
, 570
void, , 56, 79
, 266
W
\W, , , 217, 221
\w, , , 217, 221
W3C
XPath API, 535
API
HTML, 395
W3C DOM, , 23, 314, 315, 323
HTML API, 326
XML API, 524
HTML, 524
, ,
332
DOM, 331
, 334
, 276
, 323
XML, 526
watch(), , 599
WHATWG (
), 274
while, , 105
continue, , 111
width, , 370, 381
width,
Image, , 52
Screen, , 294
,
, 54
Window, , 74, 253, 909
back() forward(), , 291
clearInterval(), , 288
clearTimeout(), , 288, 507
document, , 314
frames[], , 308
getComputedStyle(), , 395
getSelection(), , 357
history, , 291
JavaScript
, 309
Location, , 289
onerror, , 304
open(), , 413
prompt(), , 162
screen, , 890
setInterval(), , 288, 391
setTimeout(), , 288, 392, 507
, 292
listanchors(), 322
, 270
(), 300
, 299
, 302
, 299
, , 912
, 913, 920
, 909
, 271
, 299
, 924
, 266
window, (Window), 74, 253, 911
with, , 413
967
write(), , 259
Document, , 24, 29, 268, 316
onload, , 269
open() close(), 316
, 317
writeln(), (Document), 317
X
X Y , 424,
426
XHTML
defer, , <script>, , 262
JavaScript CDATA, 258
SVG, 562
XML, 518
CDATASection, , 749
DOM API,
, 524
HTML DOM, , 524
HTML XML,
526
E4X (ECMAScript XML), 543
, 22
SVG, 562
VML, 569
XPath, , 531
XSLT, ,
528
, 540
, 759
XMLHttpRequest, 499
HTTP, 506
XML, 518
, 520
XML, 522
XML, 521
, 519
HTML, 537
XML
CSS XSL, 529
XML.Transformer, , 530
<xml>, , XML
, 522
XMLDocument, , 483
XMLHttpRequest, , 495, 929
abort(), , 508
GET, , 502
load(), , 521
POST, , 504
, 930
, 499
, 507
, 513
HTML, XML
JSON, 505
, 497
, 282
XML, 518
, 503
, 498
, 931
, 502
, 496
XMLHttpRequest(), , 496
XMLSerializer, , 536, 936
XPath, 531
getNode() getNodes(),
, 538
W3C API, 535
, 532
XPathExpression, , 937
XpathResult, , 938
XSLT ( XSL), 528
XSLTProcessor, , 941
XSS ( ), 283
XUL (XML User interface Language
XML
), 286
Z
zindex, (CSS), 370, 378
, 193
, 156
,
, 134
, 219
XML Java
Script, 521
, 277, 296
, 552
DHTML, 391
, 304
, 392
CSS, 392
Button
, 394
968
, 163
, 406
, 588
<applet>, , name , 460
applets[], , 319, 816
canvas,
, 581
, 590
, 591
Common DOM API, 596
, JSObject, 594
, 139, 143
Argument, , 144
URL, 289
, 146
, 143
, 143
, 146
, 41, 81
, 78, 81
, 52
, 54
, 125
, 285
CSS, 361
CSS2Properties, , 753
display visibility, 378
textshadow, 373
JavaS
cript, 387
,
362
HTML
class, 366
style, 368
,
JavaScript, 328
, 342
, 321, 404,
407, 411
Image, 833
,
DOM, 326
XML, 525
, 791
onclick, 405
onmouseover, 405
onsubmit, 405
, 412
cookie , 474
History, , 291
XMLHttpRequest, , 501
Java
JavaScript, 595
Java, 593
, 317
, 493
JavaScript, 280
, 283
,
280
,
281
, 681
, 82
, 100
send(), 498
, 302
(CSS), 379
, 70
, 325
, 267
, 23, 251
DOM, , 329
, 331
Location History, , 289, 291
Window, Screen Navigator,
, 291
XMLHttpRequest ,
readyState 3, 501
JavaScript HTML,
251, 258
defer, , 262
<script>, , 258
,
, 416
, 423
, 302
, 812
DOM, 253
JavaScript
, 268
JavaScript, 260
, 297
, 299
, 306
, 304
HTML, 264
cookie, 476
, 253
, 311
CSS, 368
, 252
, 287
DOM, 329
, 329
,
273
,
274
online ,
273
IE, 277
, 288
, Mozilla,
JavaScript, 28
cookie, 476
, 317
, SOAP, 540
cookies, 473
, 546
Flash, 576
Java, 581
SVG, 562
VML, 569
CSS, 368
, 295, 859
,
JavaScript, 40
, 41
, 47
, 48
969
, 309
, 370, 378, 383
cookies, 473
, 299
, 54
, 133
, 53
else, 102
, 141
, 157
, 139
, 410
, 40
cookie, 473, 476
IE, 428
, ,
415
, , 297
, Ajax, 511
slice(), 135
splice(), 135
unshift(), 136
JavaScript
defer, , 262
onload, , 269
onunload, , 270
<script>, , 258
, 264
HTML, 258
Java, 229
, 251
JavaScript, 236
JavaScript, 285
, 235
URL Java
Script, 269
, 260
javax.script, 234
Java
Script, 236
, 263
, 259
, 369
, 139
HTML,
, 356
970
, 39, 139
(), , 52
apply() call(), , 153
, 417
, 74, 156
, 156
throw, , 115
XPath, 531
, 81
, 54
, 533
, 77
case, 105
return, 114
, 77
, 99
,
53
, 77
, 77
, 80
, 56
, 141
, 110
, 395
, , 42, 79, 82
, 292
,
Window, 299
CSS, 556
Function(), 164
, 159
, 199
, 204
, 223, 225,
228
, 222
,
, 546
, 546
<canvas>, , 274, 572
Java, 581
CSS, 555
SVG, 562
VML, 569
,
547
, 191
,
219
JavaScript 1.5, 220
, 318
, 288
, HTML
, 316
IE, 482
, 91
, 79
, , 42
, , 79, 82
, 24, 302
confirm(), , , 303
JavaScript
, 302
, 29
,
315
( Text), 341
, 855
, 290
, 292
, 855
, 314
, 68
, JavaScript, 279
, 325, 334
, 342
, DOM, 324
, 334
, 341
, 219
,
217
,
, 281
, , 157
, 159
IE, 162
, 37
, 37
ECMAScript v3, 37
, 216
, 39
null, 55
undefined, 55
, 53
, 61
, 51
, 50
(&), , 91
, 36
arguments, 144
DOM, 422
, 182
, 253
HTML, 324
, 107
, , 392
971
, 549
, 549
, 548
(XOR) (^), ,
91
(|), , 91
, 76
, 52
0,
46
, 53, 129
, 131
, , 131
with, 119
, 54
, 203
, 107
, 168
, 178
, 99
break, 110
continue, 111
else if, 102
function, 113, 139
if, 101
return, 104, 114, 140
switch, 103
throw, 115
try/catch/finally, 116
with, , 119
, 264
972
, 126
, 109
, 99
, 100
, 288
JavaScript
Java, 229
Java, 237
Mozilla, 230
, 43
, 218
, 444
, 441
, 279
, 300
, 407
, 299
, 240
, 165
Circle, (), 175
className, , 361
CSS, 396
Java
JavaClass, 240
JavaPackage, , 239
JavaScript, 172
, 241
, 244
Java C++, 173
Object, , , 178
, 202
(), 176
, 165
, 166
, 180
, 182
,
185
, 185
, 189
, 166
,
170
, 168
JavaScript, 165
, 186
, 173
, 174
, 174
, 173
, 178
, 173
, 57
(
), 216
,
CSS, 366
JavaScript, 23, 251
, 280
,
285
, 283
,
280
, 280
973
,
281
URL, 266
, 309
HTML, 258
, 279
, 271
HTML, 264
, 546
, 314
, 29
, 273
,
275
, 277
,
274
, 274
, 723
, 252
(), 344
break, 104
case, 104
catch, 116
CSS, 361
do, 106
finally, 116
float, 387
for, 108
function, 139, 163
in, 108
switch, 103
this, 151, 174
try, 116
undefined, 55
var, 68
while, 106
HTML,
Java
Script, 328
, 462
, 463
, 426
, 440
, 651
, HTTP, 498
, 319
, 320
, 35
HTML <script>, 263
, 147
IE, 277
, JSObject,
594
Java, 235
, ,
176
+, , 45, 79, 81
String, ,
+, 59
,
133
, 668
Infinity, NaN Number, 42
, 170
, 185
, 51, 165
prototype, , 167
, 74, 309
X Y
, 300
, ,
292
, 435
, 424, 426
, 63
, 62, 64, 65
,
<canvas>, 574
JavaScript Java,
583
JavaScript SVG, 565
JavaScript VML, 570
Flash, 578
JavaScript , 260
, 549
, 80
, 156
974
, 157
, JavaScript, 33
, 37
, 36
, 35
, 36
Unicode, 33
,
, 310
, 36
, 77
, 56, 214
, 41
, 54
, 122
, 51, 141
, 39
Java,
JavaScript, 596
java.lang.Boolean.FALSE, 248
JavaScript,
Java, 595
, 89
(&&), 89
(||), 90
(!), 91
, 49
Boolean, , 58
null, , 55
undefined, , 56
,
, 80
, 89
, 49, 58
, 66
, 84
, 643
, 128
, 714, 715
, 683
, 623
, 689
, 626, 627
, 69
, 74
, 51
, 619
, 39, 53, 129
Array, , , 133
, 137
JavaArray, , 244
JavaScript,
Java, 247
, 52
, 132
, 131
, 97
(
), 54
, 63
, 54
, 54, 133
, 132
, 125, 129
DOM, ,
332
Arguments, , 144
, 193
, 65
, 225
, 60
, 60
,
149
, 54, 245
newArray(), 96
, 84
, 131
, 132
, 130
, 36
, 54
(XSS), 283
, 215
, 24, 51, 139, 149, 166, 172
Function, , 152, 153
HTTP, 497
Java, 243
JavaScript, 237
, 243
, 244
, 302
JavaScript, 590
975
, 186
, 419
, 175, 240
Object, 178
toString(), 178
valueOf(), 179
, 180
,
170
, 150
, 174
(DOM), 333
, 54, 133
JavaArray, 244
concat(), 135
, 223
, 404
DOM Level 2, 414
Internet Explorer, 404
, 404
, 404, 414
, JavaScript, 271
, 198
DOM, 329, 330
Events, 419
, 329
, 208
, 203
, 202
, 202
, 206
, 204
, 199
, 199
, 201
Java, 588
Common DOM API, 596
, 592
, Java
JavaScript, 592
, 33
, 182
Object, , 182
, 185
, , 813
Ajax, 515
, 172
, 182
Object, 127
, 182
, 166
,
170
, 168
, 186
, 687
(~), , 92
, 549
, 219
, 66
, 51
JavaScript, 204, 256
DOM Scripting Task Force,
The JavaScript Manifesto, 257
, 549
, 71
, 56
void,
97
, 124
, 71
, 55
, 67
, 156
Function(), ,
, 164
,
157
, 156
976
, 662
, 207
, 310
, 156
, 156
, 71
, 412
, 74, 156
, 69, 75
addEventLis
tener(), 417
with, 118
, 156
,
try/catch/finally, 116
Level 0, 404
Level 2, 414
(), 437
,
450
, 304, 403
, 24, 255, 403
Document, , 321
HTMLElement, , 824, 828
Image, , 834
Input, , 837
JavaScript, 457
Link, , 851
onload, 269, 449
onreadystatechange, 500
onsubmit onreset, 454
onunload, 270
Textarea, , 906
Window, , 913, 920
XMLHttpRequest, , 931
HTML, 264
, 465
, 410
document.write(), 269
,
272
/
, 316
URL JavaScript, 269
this, 411
, 271
, 407
, 408
, 405
, 412
HTML, 405
, 416
, 418
IE, 427, 429
addEventListener(), 417
, 416
IE, 430
,
, 409
, 25, 461
, 410
, 108
, JavaScript, 590
Java, /, 242
, 74, 76, 156
, 58
, 53
, 20, 39, 51
delete, , 96, 99
Error, 57
Function, 152
HTML, , 264
Java
JavaObject, , 242
Java
Script, 237
JavaScript, 237
Bindings
JavaScript,
234
, 74, 76, 156
, 74
, , 97
, , 253
, 52, 125
, 63
, 39, 129
, 150
, 333
,
, 254
, 166
Object, 182
, 58
, 172
, 189
,
74
, 109, 124
, 138
JavaScript, 332
, 417
Java, 247
, 53, 58
, 60, 85, 128
, 178
, 149
, 85
, 153, 658, 688
, 167
, 418
, 173
, 52, 122, 124
new, 165
, 84
, 46
, 125
, 39, 152
, 73
/
, 207
, 36
, 58
, 60
, 310
, 71
, 68, 112
, 69
HTML, 381
XMLHttpRequest, 507
, 299
, 271
, 513
977
978
, ,
273
for/in, 30
,
<head>, 310
,
, 348
URL, 290
, 86
in, , 87
valueOf(), 180
,
217
(Infinity),
42, 681
, 928
Error, , 115
onerror, , 554, 835
RangeError, , 694
ReferenceError, , 695
SyntaxError, , 716
TypeError, , 717
, 115
, 57
, Java
JavaPackage, 239
JavaScript, 239
, 241
,
( ), 73
(),
311
, , 46
\n, , 43
,
45
Java, 244
, 65
, 62
, 65
, 463
, 67
with, 118, 119
for/in, 108
, 36
JavaClass, 241
, 74
, 74
, 74
(
), 74, 156
, 71
, 75
, 69, 253
, 69
, 56, 71
, 73
null, 55
, 309
, 106
, 67
,
, 107
, 71
, 106
, 185
(), 437
(
IE), 428
,
, 415
addEventListener(), , 416
, 437
, 124, 128
propertyIsEnumerable(), , 128
, 689
, 372, 373
, 307
, 61
, 66
, 66
,
, 84
, 63
, 61
, 65
,
, 64
, 65
, 66
, 180
,
, 84
, 63
,
218
, 219
, 182
, 185
, ,
185
, , 225
,
219
CSS, 370
visibility display, , 378
, 371
,
384
, 368
, overflow clip,
, 383
,
, 388
HTML,
300
,
, 56, 224
, 281
, 282
XMLHttpRequest, 501
, 306
979
,
, 204
, 292, 299
/
, , 42
, 382
(), 384
, JavaScript, 590
Java, 240
, 285
, 91
, 80
HTML,
378
, ,
45
, 83
, 325
CSS, 398
, 400
, 368
, 399
, , 154, 155
, 325
,
, 365
Java JavaScript, 590
, 83
, 78, 80
CSS,
, 368
, 99
DOM, 329
, 275
, 107
, 255
, 382
, Java
Script , 260
HTML
, 258
, 282
HTML
XML, 904
980
, 198
E4X , 545
SVG, 566
VML, 569
XPath, 532
, 208
, 206
,
, 206
, 156
, 199
, 199
, 201
, 792
, 771
, 153, 688
, 183
, 172
, 170
, 168
JavaScript, 165
, 676
, 119
, 130
, , 165
, 61
, 83
XML, 537
, 292, 299
, 294
, 131
, 76, 118
,
CSS, 382
,
, 319
, 415
DOM Level 2, 423, 437
MIME, 856
, , 87
addEventListener()
this, 418, 429
, 418
IE, 427
,
418
, onload, 449
, 416
, 40, 214
RegExp, , 226, 695
, 467
, 708
String, 223
, 214
,
, 219
,
221
, 216
, 216
, 215
, 222
, 215
, 219
, 707, 710
, 217
Perl RegExp
, 223
(IE), 381
, 325
Flash
, 599
, 598
, 73
Internet Explorer, 162
, 51
constructor, 127
HTML API (DOM), 328
,
328
, 53
, 132
, 174
, 123, 173
constructor, ,
, 127
CSS2Properties, 387
Form, 454
JavaScript,
CSS, 386
undefined, 55
Window, , 271
, 253, 660
[],
125
,
, 410
, 146
, 408
Ja
va, 243
, 109
, 689
DOM API JavaScript,
332
, 51
, 52
, 254
, 125
, 178
, 168
, 152
prototype, 153
, 173
, JavaScript
relative, 558
, 91
(<), 92
(>>>),
92
(>>), 92
, 406
, 415, 428
, 451
XML, 536, 936
, 36
, 215
, 45
, 466
, 42
, DOM, 315
(listeners) , 416
, 335
981
(), 187
, 255, 403
, 406
, 264
, 406
, 415, 428
, 416
, 280
, 421
, 450
, 440
, 441
, 440
, 442
, 435
(), 437
IE, 428
, 435
, 406
, 404
DOM, 419
, 416
, JavaScript
, 273
, 274
HTML, 314
, 343
Java, 584
(new), 95
, 134
, 100
,
481
Flash SharedObject, 483
PObject, , 485
userData, 481
, 493
cookies, 481
(), 485
( Arguments), 144
, 63, 66
, 63, 64
, 66, 87, 88
982
, 180
, 60
, 88
,
, 134
(),
344
, 267
links[], , 319, 817
, 53
, 219
, 462
, 283
Window, 271
Java,
JavaScript, 237
, 309
URL
, 411
, 318
, 61
, 84
, HTML
, 322
, 281
, 63, 71
,
, 64
, 71
, 65
,
404, 414
addEventListener()
this, 418
, 421
, 419
(), 437
, 415
,
416
, 418
(IE), 381
, 320
, ,
, 136
, CSS, 361
color, 382
visibility display, 378
zindex, 378
JavaScript, 387
, 365
, 370
,
386
, 362
, 68
, 125
, 303
, 39, 43
Java, Java
Script, 596
JavaScript, Java
, 595
String, , 58
, 88
, 45
null, 55
, 52
, 63
, 45
, 128
,
, 223
, 45
, 56
, 88
, 57
, 48
, 426
, 137
Date
, 56
, 127, 178
, 46
, 133
, 87
, 84
, 43
, 43
, 72
, 73
, 289
983
, 43
, 268
, 29
, 365
XSLT, 528
, 288, 403
HTML, , 258
,
Text, 341
(
CSS), 373
, 464
, 80, 94
, 81
, 68
, 39
null, 55
undefined, 55
, 146
, 41
, 125
, 49
, 39, 53, 122, 129
, 78
, 67
,
71
, 57
Java JavaScript, 234, 245, 595
Date, 56
, 39, 122
, 127
,
60, 128, 179
, 46
, 51, 148
, 39
, 71
, 58
, 161
, 684
, CSS zindex,
378
, 670
, 132
cookie, 476
pop(), 136
shift(), 136
Option Select,
466
, 68
Text, 341
, 131
splice(), 135
, 514
, 325
Attr, 326
dispatchEvent(), , 450
DocumentFragment, 342
HTMLElement, innerHTML, ,
351
(), 342
, 334
, 325
,
341
, 340
HTML
DOM, 324
, 341
,
424
,
343
Element Text, 343
, 349
X Y, 424
, 42, 79, 82
, 80, 82
delete, , 96
new, , 95
typeof, , 94
, 81
(UTC), 626, 627
Date, 628
, 255
, 43
, 43
DOM, 328
, 101
984
IE, 277
, 94
IE, 162, 430
, , 29
, , 222, 228
, 34
, 302
, 562
, 453
fieldset, 467
forms[], , 319
, 459
(), 467
, 460
, 455
HTTP POST, 504
, 463
,
, 457
, 461
, 466
, 407
<select>
, 320
, 342
, 306, 913
location, , 289
JavaScript, 253
JavaScript
, 281
/
, 316
, 307
, 309
, 282
, 306
, 311
, 310
, 39, 50, 139
return, , 114
, 163
, 143
,
146
, 143
,
145
, 146
, 163
, 139
, 50, 139
Java, 236
, 660
, 186
, 51
, 142
, 204
, 148
, 149
, 150
, 63
, 152, 165
, 74
, 76
, 668
, 153
, 69
, 255, 457
IE, 427
, 156, 412
, 417
, 409
, 416
, 74, 156
, 69
, 50, 139
, 70
, 50
Java, 247
, 190
, 152
length, , 152
, 153
, 310
, Argument, 144
, 84
, ,
134
, 417
, 141
985
, 410
, 661
new, 95
, 123
, 310
, ,
441
, 141
, 142
, ,
472
, 415
, 40
, 40
, 54, 131
,
, 91
, 48
, 76, 118
Window , 253
, 309
,
HTML, 412
, ,
162
do/while, 106
for, 107
for/each/in, 545
for/in, 108
, 30
while, 105
break,
110
continue, 111
, 126
ASCII, ,
217
, 36
, 628
, 160
, ,
206
, 178
, 39
Java, / Java
Script, 234
NaN, 663
null, , 55
Number, , 58
, 41
, ,
176
,
, 63
, 56
, 41
Java Java
Script, 248, 596
JavaScript
Java, 247, 595
, 58
, 46
, 53, 60
, 85
, 84
, 40
, 47
, 173
, 175
, 174
Circle, 175
, 174
, 173
, 40
, 48
Latin1
Unicode, 44
, 173
RegExp, , 228
986
, 174
, 165, 173
, 292
,
41, 682
, 47
, 39
, 63
, 58
, 71
,
59
, 60, 85, 128,
179
, 63
id, , 366
HTML
,
404
, CSS, 376
, 378
, 408
, 326
, 129
slice(), 135
, 130
, 342
, 335
, 453
, 459
, Window, 924
, 549
, 548
,
, 68
anchors, , 816
anchors[], , 319
HTML, 300
, 221
, 222
, 323