Вы находитесь на странице: 1из 322

John Resig

Pro JavaScript
Techniques

JavaScript

2008

................................................................................................................................................................................................................. 7
............................................................................................................................................................................ 7
....................................................................................................................................................................................... 7
1 . JavaScript............................................................................................. 9
- JavaScript........................................................................................................................................... 9
................................................................................................................................................................................... 10
................................................................................................................................................. 11
DOM- ..................................................................................................................................... 12
(DOM).............................................................................................................................................. 13
......................................................................................................................................................................................................... 14
JavaScript CSS ........................................................................................................................................................................................ 15
Ajax.................................................................................................................................................................................................................. 15
................................................................................................................................................... 18
.......................................................................................................................................................................................................... 21
2 . - JavaScript ............................................................................................................ 22
................................................................................................................................................................................................ 22
........................................................................................................................................................................................................... 22
........................................................................................................................................ 24
....................................................................................................................................................... 28
........................................................................................................................................................................... 29
........................................................................................................................................................................................................ 32
- JavaScript .............................................................................................................................. 34
........................................................................................................................................................................................................ 34
.................................................................................................................................................................................. 35
.................................................................................................................................................................................. 36
........................................................................................................................................................................................ 37
............................................................................................................................................................... 38
................................................................................................................................................................................ 40
................................................................................................................................................................................................................ 40
3 . ................................................................................................................ 41
- ...................................................................................................................... 41
............................................................................................................................ 41
............................................................................................................................................................... 42
Base ....................................................................................................................................................................................... 45
Prototype ............................................................................................................................................................................. 47
............................................................................................................................................................................................. 50
...................................................................................................................................................... 51
Dojo ................................................................................................................................................................................................................. 51
YUI.................................................................................................................................................................................................................... 53
...................................................................................................................................................................... 53
...................................................................................................................................................................... 54
!= == !== ===............................................................................................................... 54
.......................................................................................................................................................................................... 55
......................................................................................................................................................................................... 55
................................................................................................................................................................................................................. 56
JSMin ............................................................................................................................................................................................................... 56
Packer ............................................................................................................................................................................................................. 57
............................................................................................................................................................................................. 58
................................................................................................................................................................................................................ 59
4 . ...................................................................................................... 61
............................................................................................................................................................................................................... 61
........................................................................................................................................................................................ 61
Internet Explorer ........................................................................................................................................................................................ 61
Firefox ............................................................................................................................................................................................................. 62
Safari............................................................................................................................................................................................................... 63
Opera..................................................................................................................................................................................................................... 64
DOM ............................................................................................................................................................................................ 65
DOM, Firefox ........................................................................................................................................... 65
DOM-, Safari ............................................................................................................................................. 66
................................................................................................................................................... 67
Firebug............................................................................................................................................................................................................ 68
Venkman........................................................................................................................................................................................................ 69
.................................................................................................................................................................................................... 70
JSUnit .............................................................................................................................................................................................................. 70
J3Unit .............................................................................................................................................................................................................. 72
Test.Simple................................................................................................................................................................................................... 73
................................................................................................................................................................................................................... 74
5 . ................................................................................................................................... 76
......................................................................................................................................... 76
DOM .......................................................................................................................................................................................... 76
DOM ............................................................................................................................. 79

3
DOM- ......................................................................................................................................... 81
HTML-.................................................................................................................................................... 82
DOM ......................................................................................................................................................................... 83
HTML DOM................................................................................................................................................................ 85
............................................................................................................................................................ 85
DOM .................................................................................................................................... 86
DOM .......................................................................................................................................... 86
HTML ..................................................................................................................................... 89
.................................................................................................................................. 89
CSS ................................................................................................................................ 90
cssQuery ........................................................................................................................................................................................................ 91
jQuery ............................................................................................................................................................................................................. 91
XPath ............................................................................................................................................................................................................... 92
........................................................................................................................................................ 93
, ................................................................................................................ 94
HTML, .................................................................................................................. 95
.............................................................................................................................................................. 96
................................................................................................................................ 97
DOM ...................................................................................................................................................................................... 100
DOM ..................................................................................................................................... 100
DOM ......................................................................................................................................................................................... 101
DOM HTML ................................................................................................................................................................. 103
DOM ...................................................................................................................................................................... 105
................................................................................................................................................................................................................. 107
6 . ................................................................................................................................................................................. 108
JavaScript.............................................................................................................................................................. 108
........................................................................................................................................ 108
JavaScript.................................................................................................................................................................................... 108
...................................................................................................................................................... 109
........................................................................................................................................................................................... 110
.......................................................................................................................................................................... 113
....................................................................................................................................................................................... 113
this.............................................................................................................................................................................. 113
.................................................................................................................................................... 114
....................................................................................................................................... 116
....................................................................................................................................................... 118
...................................................................................................................................................................... 119
...................................................................................................................................... 119
......................................................................................................................... 120
DOM-: W3C ................................................................................................................................................................................... 120
W3C-.......................................................................................................................................................... 121
W3C-................................................................................................................................................................. 121
DOM-: IE ........................................................................................................................................................................................ 121
IE-............................................................................................................................................................... 122
IE-...................................................................................................................................................................... 122
addEvent removeEvent............................................................................................................................................................................ 122
addEvent...................................................................................................................................................................... 124
addEvent............................................................................................................................................................................. 125
................................................................................................................................................................................................. 125
DOM- ........................................................................................................................................ 126
JavaScript.................................................................................................................................... 126
JavaScript................................................................................................................ 127
CSS ...................................................................................................................................................... 127
............................................................................................................................................................................ 128
................................................................................................................................................................................................................. 129
7 . JavaScript CSS................................................................................................................................................................. 130
............................................................................................................................................................. 130
........................................................................................................................................................................... 132
.................................................................................................................................................................................. 132
............................................................................................................................................................................... 137
................................................................................................................................................................................. 139
..................................................................................................................................................................................... 140
.............................................................................................................................................................................. 143
.......................................................................................................................................................................................................... 145
.............................................................................................................................................................................................. 145
............................................................................................................................................................................................... 146
.............................................................................................................................................................................................................. 147
................................................................................................................................................................... 147
...................................................................................................................................................................................... 148
..................................................................................................................................................................................... 148
.................................................................................................................................................................. 149
....................................................................................................................................................... 149
................................................................................................................................................................. 150
............................................................................................................................................................................................ 151
...................................................................................................................................................................................................... 156
moo.fx jQuery........................................................................................................................................................................................ 157
Scriptaculous.............................................................................................................................................................................................. 158

4
.......................................................................................................................................... 158
............................................................................................................................................................. 159
................................................................................................................................................................................................................. 160
8 . ...................................................................................................................................... 161
.......................................................................................................................................................................... 161
............................................................................................................................................................................... 164
............................................................................................................................................................................... 166
................................................................................................................................................................ 166
URL................................................................................................................................................................................................................. 166
.............................................................................................................................................................................. 167
............................................................................................................................................................................................................... 168
........................................................................................................................................................................................... 168
................................................................................................................................................ 170
.................................................................................................................................................... 170
..................................................................................................................................................... 174
, ....................................................................................................... 174
........................................................................................................................... 175
.............................................................................................................................................. 176
.......................................................................................................................................... 176
.............................................................................................................................................................................. 176
........................................................................................................................................................... 179
.............................................................................................................................................................................................................. 180
9 . ........................................................................................................................... 182
.......................................................................................................................................................................................... 182
Lightbox ....................................................................................................................................................................................................... 182
ThickBox ...................................................................................................................................................................................................... 184
......................................................................................................................................................................................... 186
............................................................................................................................................................................. 188
............................................................................................................................................................................. 190
................................................................................................................................................................. 192
.......................................................................................................................................................................................................... 196
................................................................................................................................................................... 198
................................................................................................................................................................................................................. 201
1 0 . Ajax ........................................................................................................................................................... 201
Ajax .................................................................................................................................................................................... 202
HTTP- ................................................................................................................................................................................................. 202
......................................................................................................................................................................... 203
......................................................................................................... 204
GET-......................................................................................................................................................................... 206
POST- ...................................................................................................................................................................... 206
HTTP .................................................................................................................................................................................................. 208
................................................................................................................................................................................. 209
........................................................................................................................................ 210
.................................................................................................................................................................. 211
Ajax-.......................................................................................................................................................................... 212
................................................................................................................................ 215
RSS-, XML................................................................................................................................... 215
HTML............................................................................................................................................................................................ 217
JSON JavaScript: ............................................................................................................................... 218
................................................................................................................................................................................................................. 219
1 1 . Ajax........................................................................................ 220
........................................................................................................................................................................................ 220
................................................................................................................................................................................................. 220
.......................................................................................................................................................................................... 223
.................................................................................................................................................... 224
................................................................................................................................................................................................................ 225
.......................................................................................................................................................................................................... 226
............................................................................................ 229
................................................................................................................................................................................................................. 232
1 2 . ............................................................................................................................................. 233
........................................................................................................................................................ 233
................................................................................................................................................................................. 235
..................................................................................................................................................... 236
........................................................................................................................................................................... 240
............................................................................................................................................................ 243
......................................................................................................................................... 243
..................................................................................................................................................... 244
........................................................................................................................................................................ 244
................................................................................................................................................................................................................. 250
1 3 . Ajax Wiki............................................................................................................................................................................. 251
Wiki? .............................................................................................................................................................................................. 251
....................................................................................................................................................................... 252
Ajax-...................................................................................................................................................................................................... 253

5
............................................................................................................................................................................ 254
................................................................................................................................................................................ 254
SQL ............................................................................................................................................ 256
JSON-............................................................................................................................................................................. 258
: JavaScript .................................................................................................................... 259
............................................................................................................................................................................................ 260
JavaScript ..................................................................................................................................................................... 261
JavaScript SQL- ................................................................................................................................................................ 264
Ruby- ........................................................................................................................................................... 265
................................................................................................................................................................................................................. 268
1 4 . JavaScript? ............................................................................................ 269
JavaScript 1.6 1.7...................................................................................................................................................................................... 269
JavaScript 1.6............................................................................................................................................................................................ 269
ECMAScript XML (E4X).................................................................................................................................................................. 269
....................................................................................................... 271
JavaScript 1.7............................................................................................................................................................................................ 272
............................................................................................................................................................................. 272
(Let Scoping) ........................................................................................... 273
.................................................................................................................................................................................. 274
Web Applications 1.0 .................................................................................................................................................................................... 275
........................................................................................................................................................................................ 276
............................................................................................................................................................................. 280
Comet.................................................................................................................................................................................................................. 282
................................................................................................................................................................................................................. 285
. DOM................................................................................................................................. 287
Resources .......................................................................................................................................................................................................... 287
................................................................................................................................................................................................. 287
......................................................................................................................................................................................................... 288
........................................................................................................................................................................................................ 288
.................................................................................................................................................................................. 288
Document ................................................................................................................................................................................. 288
....................................................................................................................................................................................................... 288
....................................................................................................................................................................................................... 288
............................................................................................................................................................................................................... 288
...................................................................................................................................................................................................... 288
.......................................................................................................................................................................................................... 289
....................................................................................................................................................................................... 289
.......................................................................................................................................................................... 289
document..................................................................................................................................................................................................... 289
HTMLElement ............................................................................................................................................................................................. 289
DOM ................................................................................................................................................................................ 290
body............................................................................................................................................................................................................... 290
childNodes................................................................................................................................................................................................... 290
documentElement .................................................................................................................................................................................... 290
firstChild....................................................................................................................................................................................................... 291
getElementById( ID ) ................................................................................................................................................................... 291
getElementsByTagName( )................................................................................................................................................ 291
lastChild ....................................................................................................................................................................................................... 292
nextSibling .................................................................................................................................................................................................. 292
parentNode ................................................................................................................................................................................................. 293
previousSibling.......................................................................................................................................................................................... 293
................................................................................................................................................................................... 293
innerText...................................................................................................................................................................................................... 293
nodeName ................................................................................................................................................................................................... 294
nodeType ..................................................................................................................................................................................................... 294
nodeValue.................................................................................................................................................................................................... 295
........................................................................................................................................................................................................... 296
className ................................................................................................................................................................................................... 296
getAttribute( )............................................................................................................................................................... 296
removeAttribute( ) ...................................................................................................................................................... 297
setAttribute( attrName, attrValue ).................................................................................................................................................. 297
DOM ...................................................................................................................................................................................... 298
appendChild( ) ................................................................................................................................................... 298
cloneNode( true|false ).......................................................................................................................................................................... 298
createElement( ) .................................................................................................................................................................... 299
createElementNS( _, ) .................................................................................................................. 299
createTextNode( ) ............................................................................................................................................... 300
innerHTML ................................................................................................................................................................................................... 300
insertBefore( , ) ........................................................................................ 301
removeChild( ) ........................................................................................................................................................ 301
replaceChild( , ) .............................................................................................................. 302
. .................................................................................................................... 303
............................................................................................................................................................................. 303
................................................................................................................................................................................................. 303
............................................................................................................................................................................................ 303
/ / .......................................................................................... 303

6
..................................................................................................................................................................................................... 303
........................................................................................................................................................................................................... 303
( )................................................................................................................ 304
....................................................................................................................................................................................................... 304
............................................................................................................................................................................. 304
.................................................................................................................................................................................................. 304
............................................................................................................................................................................................. 304
....................................................................................................................................................................................... 304
type................................................................................................................................................................................................................ 304
target / srcElement ................................................................................................................................................................................. 305
stopPropagation() / cancelBubble ..................................................................................................................................................... 305
preventDefault() / returnValue = false........................................................................................................................................... 306
........................................................................................................................................................................................ 307
clientX / clientY ......................................................................................................................................................................................... 307
pageX / pageY ........................................................................................................................................................................................... 307
layerX / layerY offsetX / offsetY..................................................................................................................................................... 307
button ........................................................................................................................................................................................................... 307
relatedTarget ............................................................................................................................................................................................. 308
........................................................................................................................................................................... 309
ctrlKey........................................................................................................................................................................................................... 309
keyCode ....................................................................................................................................................................................................... 309
shiftKey ........................................................................................................................................................................................................ 311
....................................................................................................................................................................................... 311
load ................................................................................................................................................................................................................ 311
beforeunload .............................................................................................................................................................................................. 312
error............................................................................................................................................................................................................... 312
resize............................................................................................................................................................................................................. 313
scroll .............................................................................................................................................................................................................. 313
unload ........................................................................................................................................................................................................... 313
(UI) ............................................................................................................................... 314
focus .............................................................................................................................................................................................................. 314
blur................................................................................................................................................................................................................. 314
............................................................................................................................................................................................... 314
click ................................................................................................................................................................................................................ 314
dblclick.......................................................................................................................................................................................................... 315
mousedown ................................................................................................................................................................................................ 315
mouseup ...................................................................................................................................................................................................... 315
mousemove ................................................................................................................................................................................................ 315
mouseover .................................................................................................................................................................................................. 316
mouseout..................................................................................................................................................................................................... 316
................................................................................................................................................................................... 317
keydown / keypress ................................................................................................................................................................................ 317
keyup ............................................................................................................................................................................................................ 318
.............................................................................................................................................................................................. 318
select ............................................................................................................................................................................................................. 318
change .......................................................................................................................................................................................................... 318
submit ........................................................................................................................................................................................................... 319
reset............................................................................................................................................................................................................... 319
. ......................................................................................................................................................... 321
............................................................................................................................................................................. 321
Internet Explorer ............................................................................................................................................................................................ 321
5.5 6.0...................................................................................................................................................................................... 321
7 ...................................................................................................................................................................................................... 321
Mozilla ................................................................................................................................................................................................................. 321
Firefox 1.0, Netscape 8 Mozilla 1.7 .............................................................................................................................................. 322
Firefox 1.5 2.0....................................................................................................................................................................................... 322
Safari............................................................................................................................................................................................................. 322
Opera............................................................................................................................................................................................................. 322
8.5.................................................................................................................................................................................................. 322
9.0.................................................................................................................................................................................................. 322

(John Resig)

JavaScript. JavaScript- jQuery,


-.
, - (http://ejohn.org/), .


(Dan Webb) -,
Vivabit, Event Wax, - .
Rails Unobtrusive JavaScript, Low Pro Prototype.
JavaScript, @media 2006, RailsConf The
Ajax Experience. A List Apart, HTML Dog SitePoint,
UK web design group the Brit Pack. - http://www.danwebb.net/
Ruby, Rails JavaScript. Prototype Core Team.


, .
,

.
, (Chris Mills), ,
. ,
, .
, (Dan Webb),
JavaScript.
.

(Jennifer

Whipple),

, (Laura Esterman),
,
.

8
, (Tracy Brown Collins),
,
.
(Julia West) (Josh King)
, .
, , ,
.
.

1 JavaScript
JavaScript , .
JavaScript , ,
.
JavaScript , ,
. , , ,
JavaScript- .
, , ,
. ,
JavaScript.

- JavaScript
, -
, - JavaScript,
-. , , JavaScript
, , ( Ruby, Python Perl)
.
-

JavaScript

, .
, , , ,
, JavaScript, .
1.1 , ,
.
1.1. - JavaScript,

// 'Lecture'
// name teacher
function Lecture( name, teacher ) {
//
this.name = name;
this.teacher = teacher;
}
// Lecture,
// ,
Lecture.prototype.display = function(){
return this.teacher + " " + this.name;
};
// ,
//
function Schedule( lectures ) {
this.lectures = lectures;
}
// , ,

10
//
Schedule.prototype.display = function(){
var str = "";
// ,
//
for ( var i = 0; i < this.lectures.length; i++ )
str += this.lectures[i].display() + " ";
return str;
};
1.1 ,
- , ,

. , ,
. 1.2.
1.2.

// Schedule
// 'mySchedule'
var mySchedule = new Schedule([
// Lecture,
// Lecture
new Lecture( "Gym", "Mr. Smith" ),
new Lecture( "Math", "Mrs. Jones" ),
new Lecture( "English", "TBD" )
]);
//
alert( mySchedule.display() );
JavaScript ,
- .
- JavaScript, , ,
.


- ,
JavaScript .
,
.

.
4 ,
, .
Firebug Firefox. ,

11
, HTTP-, . . 1.1
Firebug .

. 1.1. , Firefox Firebug


.
-
, , .


, JavaScript
.
JavaScript,
. JavaScript- data,
,
.
JavaScript-
, <script>-, , , .
,
.

JavaScript, . (
) ,
Yahoo. 1.3.
1.3. , Yahoo UI,

// mouseover ,
// ID 'body'
YAHOO.util.Event.addListener('body','mouseover',function(){
//
this.style.backgroundColor = 'red';
});

12
,
-

. , JSAN (JavaScript
Archive Network). ,
, .
JSAN . 1.2.
, 3.
, ,
, , 6.

. 1.2. JSAN

DOM-
,
DOM-.
HTML-: , , JavaScript,
.
, ,
. ,
, , , ,
.
, :
Document Object Model (DOM), JavaScript-. .

13
(DOM)
DOM XML-. ,
, ,
, - ( Java, Perl,
PHP, Ruby, Python JavaScript). DOM
XML-.

HTML

XML,

DOM-
JavaScript. JavaScript JavaScript

HTML-,

-,

DOM

. 1.4. DOM
, .
1.4.
DOM

<html>
<head>
<title> DOM</title>
<script>
// DOM,
//
window.onload = function(){
// <li>,
var li = document.getElementsByTagName("li");
//
for ( var j = 0; j < li.length; j++ ) {
li[j].style.border = "1px solid #000";
}
// , ID
// 'everywhere'
var every = document.getElementById( "everywhere" );
//
every.parentNode.removeChild( every );
};
</script>
</head>
<body>
<h1> DOM</h1>
<p class="test">

DOM

, :</p>
<ul>
<li id="everywhere"> .</li>

14
<li class="test"> .</li>
<li class="test"> ,
.</li>
</ul>
</body>
</html>
DOM JavaScript.
HTML-, JavaScript HTML.

. JavaScript,
( HTML DOM).

. DOM
JavaScript , - .
, ,
- , , ,
. , ,
. 1.5, <li>
, .
1.5. DOM

<html>
<head>
<title> DOM</title>
<script>
// DOM,
//
window.onload = function(){
// <li>,
//
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
//
// <li>,
// <li> .
li[i].onmouseover = function() {
this.style.backgroundColor = 'blue';
};
//
// <li>,
// <li> .

15
li[i].onmouseout = function() {
this.style.backgroundColor = 'white';
};
}
};
</script>
</head>
<body>
<h1> DOM</h1>
<p class="test">

DOM

, :</p>
<ul>
<li id="everywhere"> .</li>
<li class="test"> .</li>
<li class="test"> ,
.</li>
</body>
</html>
JavaScript .
, . 6
.

JavaScript CSS
DOM
HTML. HTML ,
JavaScript CSS-, DOM.
(Cascading style sheets, CSS) ,
-, ,
. , HTML
JavaScript CSS,
.

, 7, .

Ajax
JavaScript XML, Ajax , (Jesse James
Garrett), Adaptive Path, ,

Ajax:

New

Approach

to

Web

Applications

(Ajax:

(http://www.adaptivepath.com/publications/essays/archives/000385.php).

-)

, .
Ajax ,
:
.
, , . . 1.3
Ajax, ,

16
, (,
).

. 1.3. Ajax: A New Approach to Web Applications, ,


,
, ,
, ,
. , , ,
Ajax ( 2000 ).
, ,

17
(, , Internet Explorer). ,
XMLHttpRequest ( XML- ),
,
.
, ,
Ajax, Google.
Ajax Google Suggest,
.
.
, Google Suggest , . 1.4.

. 1.4. Google Suggest, Ajax


XML-
Google Google Maps,
, ,
. ,
Ajax, ,
, . Google
Maps . 1.5.
JavaScript -
, Google
Yahoo, , .

18

. 1.5. Google Maps, Ajax-



JavaScript ,
, , ,
. ,
JavaScript, ,
.
,
.
,
.
Yahoo JavaScript-,
-. ,

-.

Yahoo ,
. , ,
, , - .

19
Yahoo ,
. : A,
X C:

A , Yahoo
.

X A, Yahoo ,
, ,
. X ,
A, , .

C , ,
Yahoo. ,
, JavaScript, Yahoo
( , JavaScript).
, , Yahoo,

, .
, , Yahoo
A. , ,
(
).
,
( http://developer.yahoo.com/yui/articles/gbs/gbs.html),
, . 1.6, Yahoo .
-, Yahoo
, , .
,

. ,

A, ,
, . ,
, ,
. ( ) Netscape Navigator 4 Internet Explorer 5,
, , ,
.

20

. 1.6. , Yahoo
, ,
, .
:
JavaScript 1.5: , JavaScript,
, - JavaScript.
Internet Explorer 5.0 1.5,
.

XML Document Object Model (DOM) 2: HTML XML-.


.

XMLHttpRequest: Ajax http-.


, Internet Explorer 5.56.0;
, ActiveX.

CSS: , -.
, CSS -.
CSS , ,
. , Internet Explorer Mac
.

21
JavaScript.
,
, . ,
,
.

,
JavaScript, ,
, , .
, .
JavaScript: - ,
. ,
DOM-, ,
JavaScript CSS. , , ,
Ajax JavaScript .
JavaScript.

22

2 - JavaScript
JavaScript. JavaScript ,

, JavaScript ,
, , .
JavaScript,
, , ,
JavaScript. , ,
- JavaScript, ,
.
, , ,
JavaScript, .


JavaScript , .
. ,
.

JavaScript .
. , ,
. , .
. JavaScript.
, .
,
( , , ..).
, .
2.1, ,
.
2.1. ,

// obj
var obj = new Object();
// objRef
var objRef = obj;
//
obj.oneProperty = true;
// ,
// ( )
alert( obj.oneProperty === objRef.oneProperty );
, JavaScript
. , - .

23
, push(). Array
, , , 2.1,
(
). 2.2.
2.2.

//
var items = new Array( "one", "two", "three" );
//
var itemsRef = items;
//
items.push( "four" );
// ,
//
alert( items.length == itemsRef.length );
, , ,
. , Perl ,
, . JavaScript ,
. 2.3,
, .
2.3. Changing the Reference of an Object While Maintaining Integrity

// items ()
var items = new Array( "one", "two", "three" );
// itemsRef items
var itemsRef = items;
// items
items = new Array( "new", "array" );
// items itemsRef .
// items new Array( "new", "array" )
// itemsRef new Array( "one", "two", "three" )
alert( items !== itemsRef );
, , , ,
, .
, .
2.4.
2.4. , ,

// item

24
var item = "test";
// itemRef
var itemRef = item;
//
// , ,
// .
item += "ing";
// item itemRef ,
//
alert( item != itemRef );
, .

JavaScript.
,
, .


- ,
Java, ,
. JavaScript ,
.
:
, . .

JavaScript

arguments, , .
Arguments (..
.push( ) ),
.length. , 2.5.
2.5. JavaScript

//
function sendMessage( msg, obj ) {
//
if ( arguments.length == 2 )
//
obj.handleMsg( msg );
// ,
//
else
//
//
alert( msg );

25
}
//

// alert
sendMessage( "Hello, World!" );
// ,
//
sendMessage( "How are you?", {
handleMsg: function( msg ) {
alert( "This is a custom message: " + msg );
}
});
// ,
//
function makeArray() {
//
var arr = [];
//
for ( var i = 0; i < arguments.length; i++ ) {
arr.push( arguments[i] );
}
//
return arr;
}
, .
. , ,

undefined. 2.6 ,

, ,
.
2.6.

function displayError( msg ) {


// , msg (undefined)
if ( typeof msg == 'undefined' ) {
// ,
msg = " .";
}
//
alert( msg );
}

26
typeof . JavaScript
,
. ,
.

typeof. , .
, , object array,
, , user, object, ,
. 2.7.
2.7. Typeof

// ,
if ( typeof num == "string" )
// ,
num = parseInt( num );
// ,
if ( typeof arr == "string" )
// , ,
// ,
arr = arr.split(",");
,
JavaScript, constructor. ,
. 2.8.
2.8. constructor

// ,
if ( num.constructor == String )
// ,
num = parseInt( num );
// ,
if ( str.constructor == Array )
// ,
//
str = str.join(',');
2.1 ,
. , .
typeof ( ,
). , . , ,
.constructor ,
. , , .
2.1.

27
{ an: object }

object

Object

[ an, array ]

object

Array

function(){}

function

Function

a string

string

String

55

number

Number

true

boolean

Boolean

new User()

object

User

, 2.1,
. , , ,
.
, ,
.
2.9.
2.9.

//
function strict( types, args ) {
//
if ( types.length != args.length ) {
// ,
throw " . " + types.length +
", " + args.length + ".";
}
//
for ( var i = 0; i < args.length; i++ ) {
//
if ( args[i].constructor != types[i] ) {
throw " . " + types[i].name +
", " + args[i].constructor.name + ".";
}
}
}
// ,
function userList( prefix, num, users ) {
// , prefix , num ,
// users
strict( [ String, Number, Array ], arguments );
// 'num'
for ( var i = 0; i < num; i++ ) {

28
//
print( prefix + ": " + users[i] );
}
}

,

, .
, JavaScript, .


JavaScript .
- ;
, . JavaScript
, ( , while, if for). ,
, , ( ,
). 2.10 ,
.
2.10. JavaScript

// 'test' foo
var foo = "test";
// if
if ( true ) {
// foo 'new test'
// : !
var foo = "new test";
}
// , foo 'new test'
alert( foo == "new test" );
// , foo
function test() {
var foo = "old test";
}
// , , 'foo'
//
test();
// , foo - 'new test'
alert( foo == "new test" );
, 2.10
. JavaScript , ,
, window.
Opera Safari , - ,

29
. 2.11
.
2.11. JavaScript Window

// , 'test'
var test = "test";
// , '' test
// window
alert( window.test == test );
, , , . 2.12
foo test( ). ,
( var foo).
foo , ,
.
2.12.

// , foo
function test() {
foo = "test";
}
// foo
test();
// , foo
alert( window.foo == "test" );
JavaScript , ,
, ,
. ,
, JavaScript .

, , , ,
.
. , ,
.
, 2.13.
2.13. , ,

// , ID 'main'
var obj = document.getElementById("main");

30
//
obj.style.border = "1px solid red";
// ,
//
setTimeout(function(){
//
obj.style.display = 'none';
}, 1000);
//
function delayedAlert( msg, time ) {
//
setTimeout(function(){
// ,
//
alert( msg );
}, time );
}
// delayedAlert
delayedAlert( " !", 2000 );
setTimeout ,
JavaScript .
:

setTimeout("otherFunction()", 1000);
// ;
setTimeout("otherFunction(" + num + "," + num2 + ")", 1000);
,
. . , 1000
, obj (
, ID main). , ,
delayedAlert,

setTimeout,

.
, , ,
, ,

.
,
. (currying).
, ,
, . 2.14 ,
, .
2.14.

31
// ,
function addGenerator( num ) {
// , ,
//
return function( toAdd ) {
return num + toAdd
};
}
// addFive ,
// ,
var addFive = addGenerator( 5 );
// , addFive 9,
// 4
alert( addFive( 4 ) == 9 );
JavaScript , ,
. ,
.
,
- , . 2.15 ,
, ,
, .
2.15.

// ,
(function(){
// ,
var msg = " !";
// ,
window.onunload = function(){
// ''
alert( msg );
};
//
})();
, . ,
,
. , ,
, .
. , ,
(, i). for , ,
. , , ,

32
(, ),
, , , . 2.16
, ,
.
2.16.

// , ID main
var obj = document.getElementById("main");
//
var items = [ "click", "keypress" ];
//
for ( var i = 0; i < items.length; i++ ) {
//
//
(function(){
//
var item = items[i];
//
obj[ "on" + item ] = function() {
// ,
// for
alert( " " + item );
};
})();
}
- ;
, - , . ,
, JavaScript
(Jim Jey) JavaScript Closures http://jibbering.com/faq/faq_notes/closures.html.
, , ,
- JavaScript.

JavaScript - (,
).

, JavaScript.
this. ,
. ,
window. , this
. ,

. 2.17 .

33
2.17.

var obj = {
yes: function(){
// this == obj
this.val = true;
},
no: function(){
this.val = false;
}
};
// , 'obj'
alert( obj.val == null );
// yes val,
// 'obj'
obj.yes();
alert( obj.val == true );
// window.no obj.no,
window.no = obj.no;
window.no();
// , obj (
// window)
alert( obj.val == true );
// val window .
alert( window.val == false );
, , , 2.17
obj.no window. , JavaScript ,
. 2.18 , call apply,
.
2.18.

// ,
function changeColor( color ) {
this.style.color = color;
}
// window, ,
// style
changeColor( "white" );
// , ID main
var main = document.getElementById("main");

34
// , call
// ,
//
changeColor.call( main, "black" );
// , body
function setBodyColor() {
// apply body,
// ,
// ,
changeColor.apply( document.body, arguments );
}
// body
setBodyColor( "black" );
, ,
, - JavaScript.

- JavaScript
- JavaScript , JavaScript
-, - - .
, ( JavaScript) ,
, .
, JavaScript, ,
JavaScript, ,
.
- JavaScript,
, .

JavaScript. .
.
, - -, .
2.19 .
2.19.

// Object- 'obj'
var obj = new Object();
//
obj.val = 5;
obj.click = function(){
alert( "hello" );
};

35
// ,
// {;} -
var obj = {
//
// -
val: 5,
click: function(){
alert( "hello" );
}
};
. ,
, .


- , JavaScript
. -
, JavaScript . JavaScript ,
.
.
- JavaScript ,
. JavaScript ,
. , .
( ) (
, ).
, , 2.20.
2.20.

// ,
//
function User( name ) {
this.name = name;
}
//
var me = new User( "My Name" );
// ,
//
alert( me.name == "My Name" );
// User
alert( me.constructor == User );
// , User() - , ,

36
// ?
User( "Test" );
// 'this' ,
// 'window', ,
// window.name
alert( window.name == "Test" );
2.20 constructor. ,
, , .
, ,
. 2.21.
2.21. constructor

// , User
function User() {}
// User
var me = new User();
// User ( ,
// )
var you = new me.constructor();
// , constructor
alert( me.constructor == you.constructor );
, , , ,
: .


(Public) .
, ,
prototype (), ,
.
.
, 3.
, ,
.
, (
). 2.22.
2.22. , prototype

// User
function User( name, age ){
this.name = name;
this.age = age;

37
}
// prototype
User.prototype.getName = function(){
return this.name;
};
// prototype
// , ,
//
User.prototype.getAge = function(){
return this.age;
};
// User
var user = new User( "Bob", 44 );
// , ,
// ,
alert( user.getName() == "Bob" );
alert( user.getAge() == 44 );

JavaScript.


(Private) , ,
( ).
, .
(Douglas Crockford), - ,
- :

JavaScript: http://javascript.crockford.com/

Private Members in JavaScript: http://javascript.crockford.com/private.html


2.23 , .
2.23. , constructor

// ,
function Classroom( students, teacher ) {
// ,
function disp() {
alert( this.names.join(", ") );
}
//

38
this.students = students;
this.teacher = teacher;
//
disp();
}
// classroom
var class = new Classroom( [ "John", "Bob" ], "Mr. Smith" );
// , disp
class.disp();
,
, , .
,
, .


(Douglas Crockford) ,

2.24

),

.
2.24.

// User
function User( name, age ) {
//
var year = (new Date()).getFullYear() age;
// ,
// year,
this.getYearBorn = function(){
return year;
};
}
// user
var user = new User( "Bob", 44 );
//
alert( user.getYearBorn() == 1962 );
// , year
alert( user.year == null );
, ,
, .

39
,
, . 2.25 ,
, .
2.25. ,

// user, (properties)
function User( properties ) {
// ,
// ( )
for ( var i in properties ) { (function(){
//
this[ "get" + i ] = function() {
return properties[i];
};
//
this[ "set" + i ] = function(val) {
properties[i] = val;
};
})(); }
}
// user ,
//
var user = new User({
name: "Bob",
age: 44
});
// , (name) ,
// properties
alert( user.name == null );
// , ,
// getname(),
alert( user.getname() == "Bob" );
// , ,
// (age)
//
user.setage( 22 );
alert( user.getage() == 22 );
.

( Lisp),
. ,
.

40

, ,
. ,
. , ;
, . ,
, , .

, , 3.
2.26 , .
2.26.

// , User
User.cloneUser = function( user ) {
// (user)
return new User(
// user
user.getName(),
user.getAge()
);
};
, ,
. , .
JavaScript
, .
, , ,
.

, . ,
, JavaScript,
,
JavaScript. , ,
JavaScript.
JavaScript,
- JavaScript-.
- ,
, . ,
JavaScript,
.

41

, ,
. , JavaScript
, , ,
. JavaScript
.
,

-

,

- .

- JavaScript,
, .
(
). , - - - JavaScript,
, .
, JavaScript

, ,

,
.


JavaScript ,
. ( -,
) ,
, prototype, .
prototype ( ,
, ).
, ,
, .
,
; .
3.1. prototype
.
3.1.

// Person
function Person( name ) {
this.name = name;
}

42
// Person
Person.prototype.getName = function() {
return this.name;
};
// User
function User( name, password ) {
// ,
// -,
//
this.name = name;
this.password = password;
};
// User Person
User.prototype = new Person();
// User
User.prototype.getPassword = function() {
return this.password;
};
User.prototype = new Person( );.
. User User.
new Person( ) Person, Person.
prototype User. ,
new User( ), User ,
Person, , new Person( ).
, ,
JavaScript.


, .
, . JavaScript
, , .
, JavaScript, (Douglas Crockford),
, JavaScript
, , -
http://javascript.crockford.com/ inheritance.html.
3.2 ,
JavaScript. :
, ,
.
3.2. , JavaScript

43

// ,
//
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
// ,
// ,
// ''
Function.method('inherits', function(parent) {
// ,
//
var depth = 0;
//
var proto = this.prototype = new parent();
// '' 'uber',
// ,
//
this.method('uber', function uber(name) {
var func; //
var ret;

//

var v = parent.prototype; //
// 'uber'
if (depth) {
//
for(var i=d; i > 0;i+= 1 ) {
v = v.constructor.prototype;
}
//
func = v[name];

// 'uber'
} else {
//
func = proto[name];
//
if ( func == this[name] ) {
//

44
func = v[name];
}
}
// ,
//
depth += 1;
// ,
// ( )
ret = func.apply(this, Array.prototype.slice.apply(arguments,
[1]));
//
depth -= 1;
// ,
return ret;
});
return this;
});
//
// , , new parent()
Function.method('swiss', function(parent) {
//
for (var i = 1; i < arguments.length; i += 1) {
//
var name = arguments[i];
//
this.prototype[name] = parent.prototype[name];
}
return this;
});
, , ,
.
:
Function.prototype.method: .
, ,
method.
Function.prototype.inherits:
. this.uber('methodName')
,
. , JavaScript.

45
Function.prototype.swiss: .method( ),
.
, ,
.
, , , 3.3

Person-User,

3.1,

. ,
, .
3.3. JavaScript- ,

// Person
function Person( name ) {
this.name = name;
}
// Person
Person.method( 'getName', function(){
return name;
});
// User
function User( name, password ) {
this.name = name;
this.password = password;
},
// Person
User.inherits( Person );
// User
User.method( 'getPassword', function(){
return this.password;
});
// , Person,
// uber
User.method( 'getName', function(){
return " : " + this.uber('getName');
});
, , ,
JavaScript, ,
.

Base

46
JavaScript, Base,
(Dean Edwards).
.
. Base
, IE7, Internet
Explorer. - (http://dean.edwards.name/weblog/2006/03/base/)
, .
Base: http://dean.edwards.name/base/.
Base ,
(

Source

Code/Download

Apress

http://www.apress.com).
, -,
.
Base,
. , 3.4 ,
, .
3.4. Base

// Person
var Person = Base.extend({
// Person
constructor: function( name ) {
this.name = name;
},
// Person
getName: function() {
return this.name;
}
});

// User, Person
var User = Person.extend({
// User
constructor: function( name, password ) {
// , ,
//
this.base( name );
this.password = password;
},
// User
getPassword: function() {
return this.password;

47
}
});
, Base , 3.4,
:
Base.extend( ; );: .
, ,
.
Person.extend( ; );: Base.extend( ). ,

.extend( ),

.extend( ),

. 3.4. User
Person.
this.base();: , , this.base( ) ,
. , this.uber( ),
, (

). - JavaScript, Base

.
, Base ,
- JavaScript.
. , -
Prototype.

Prototype
Prototype JavaScript, Ruby on Rails. prototype
.
, Prototype JavaScript
Ruby. , Prototype JavaScript, JavaScript .
, , , ,
, .
Prototype - http://prototype.conio.net/. Painless
JavaScript Using Prototype http://www.sitepoint.com/article/painless-javascript-prototype/
.

Prototype

. 3.5 , Prototype .
3.5. , Prototype -
JavaScript

// 'Class',
var Class = {

48
// ,
//
create: function() {
//
return function() {
// This
this.initialize.apply(this, arguments);
}
}
}
// Object,
//
Object.extend = function(destination, source) {
//
for (property in source) {
//
destination[property] = source[property];
}
//
return destination;
}
Prototype
- . , ,
, Base .
:
Class.create(): ,
.
. , , , initialize,
; .
Object.extend():

prototype,
(, , JavaScript).
, , , Prototype, 3.6
Prototype
JavaScript .
3.6. Prototype -
JavaScript

// String
Object.extend(String.prototype, {
// HTML

49
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
//
toArray: function() {
return this.split('');
},
// "foo-bar" '' "fooBar"
camelize: function() {
//
var oStringList = this.split('-');
// ,
if (oStringList.length == 1)
return oStringList[0];
//
var camelizedString = this.indexOf('-') == 0
? oStringList[0].charAt(0).toUpperCase() +
oStringList[0].substring(1) : oStringList[0];
//
for (var i = 1, len = oStringList.length; i < len; i++) {
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}

//
return camelizedString;
}
});
// stripTags().
// , HTML,
// ,
"<b><i>Hello</i>, world!".stripTags() == "Hello, world!"
// toArray().
//
"abcdefg".toArray()[3] == "d"
// camelize().
// .
"background-color".camelize() == "backgroundColor"

50
, , Person
User, User Person. , -
Prototype, 3.7.
Listing 3-7. Prototype,

// Person
var Person = Class.create();
// Person
Object.extend( Person.prototype, {
// , Person
initialize: function( name ) {
this.name = name;
},
// Person
getName: function() {
return this.name;
}
});
// User
var User = Class.create();
// User
User.prototype = Object.extend( new Person(), {
// initialize
initialize: function( name, password ) {
this.name = name;
this.password = password;
},
//
getPassword: function() {
return this.password;
}
});
Prototype -
, ,
. , - ,
, , , Base.
-
.

51
- JavaScript (
, ),
, JavaScript.
, ,
. , ,
, .
,
. ,
. ,
,
.


,
, . JavaScript
( , , Java Python),
, , .
JavaScript , .
, , JavaScript
, , - ,

. , , ,
3.8.
3.8. JavaScript

//
var YAHOO = {};
//
YAHOO.util = {};
// ,
//
YAHOO.util.Event = {
addEventListener: function(){ ; }
};
//
YAHOO.util.Event.addEventListener( ; )

,
, , .

Dojo

52
Dojo ,
-. , ,
, ,
- . Dojo - :
http://dojotoolkit.org/.
Dojo ,
JavaScript.

. 3.9
, Dojo.
3.9. Dojo

<html>
<head>
<title>Accordion Widget Demo</title>
<!-- Dojo Framework -->
<script type="text/javascript" src="dojo.js"></script>
<!-- Dojo -->
<script type="text/javascript">
// Accordion Container widget
//
dojo.require("dojo.widget.AccordionContainer");
dojo.require("dojo.widget.ContentPane");
</script>
</head>
<body>
<div dojoType="AccordionContainer" labelNodeClass="label">
<div dojoType="ContentPane" open="true" label="Pane 1">
<h2>Pane 1</h2>
<p>Nunc consequat nisi vitae quam. Suspendisse sed nunc. Proin;</p>
</div>
<div dojoType="ContentPane" label="Pane 2">
<h2>Pane 2</h2>
<p>Nunc consequat nisi vitae quam. Suspendisse sed nunc. Proin;</p>
</div>
<div dojoType="ContentPane" label="Pane 3">
<h2>Pane 3</h2>
<p>Nunc consequat nisi vitae quam. Suspendisse sed nunc. Proin;</p>
</div>
</div>
</body>
</html>
JavaScript,
Dojo . ,
,
.

53
YUI

JavaScript Yahoo UI (http://developer.yahoo.com/yui/).


-
( ). UI-
. Yahoo UI ,
.
Yahoo UI ,
, Dojo. Dojo,
, . 3.10
Yahoo UI.
3.10. Yahoo UI

<html>
<head>
<title>Yahoo! UI Demo</title>
<!-- Yahoo UI -->
<script type="text/javascript" src="YAHOO.js"></script>
<!-- -->
<script type="text/javascript" src="event.js"></script>
<!-- Yahoo UI -->
<script type="text/javascript">
// Yahoo
// YAHOO,
// ( 'util')
YAHOO.util.Event.addListener( 'button', 'click', function() {
alert( ", !" );
});
</script>
</head>
<body>
<input type="button" id="button" value="!"/>
</body>
</html>
, Dojo, Yahoo UI,
. , ,
, .

54
. , ,
, ,
. ,
, , ,

. JSLint

, , .
- JSLint : http://www.jslint.com/.
JSLint : http://www.jslint.com/lint.html.
JSLint

(Douglas

Crockford)

, - ,
. , ,
.


, JSLint , ,
, . JavaScript
, ,
. , ,
, ?
, . JSLint
3.11.
3.11. JSLint

//
foo = 'bar';
//
var foo;
;
foo = 'bar';

!= == !== ===
, -
false, JavaScript. null, 0, , false undefined (==)
, false. , test ==
false, true, test
undefined , , .
!== ===.
( , null), ( , false). JSLint ,
false- != == !==
===. 3.12 , , .
3.12. != == !== ===

55
// true
null == false
0 == undefined
// !== ===
null !== false
false === false


, ,
, . ,
. ( , if (dog == cat )), (dog
= false;) , , .
while( ) for( ). , JavaScript,
, ,
, , .
3.13.
3.13. ,

// , Javascript
if ( dog == cat )
if ( cat == mouse )
mouse = "cheese";

// JSLint , :
if ( dog == cat ) {
if ( cat == mouse) {
mouse = "cheese";
}
}



. , JavaScript,
. , ,
, .
, , ,
3.14.
3.14. ,

// Javascript,
//

56
var foo = 'bar';
var bar = function(){
alert('hello');
};
bar();
JavaScript.
JSLint ,
,
-.

JavaScript ,
. ,
,
. JavaScript:

, ,
.

, ,
.

, , ,
, .
: JSMin Packer. JSMin

( , ), Packer
( ).

JSMin
, JSMin . JavaScript
, . JSMin
( ) .
- : http://www.crockford.com/javascript/jsmin.html.
, JSMin, (
3.15), , 3.16.
3.15.

// (c) 2001 Douglas Crockford


// 2001 June 3
// -is- .
//

// ,
// . ,
// - . , Microsoft
// IE , Mozilla 4. Netscape 6 ,

57
// version 5.
var is = {
ie:
java:

navigator.appName == 'Microsoft Internet Explorer',


navigator.javaEnabled(),

ns:

navigator.appName == 'Netscape',

ua:

navigator.userAgent.toLowerCase(),

version:

parseFloat(navigator.appVersion.substr(21)) ||
parseFloat(navigator.appVersion),

win:

navigator.platform == 'Win32'

}
is.mac = is.ua.indexOf('mac') >= 0;
if (is.ua.indexOf('opera') >= 0) {
is.ie = is.ns = false;
is.opera = true;
}
if (is.ua.indexOf('gecko') >= 0) {
is.ie = is.ns = false;
is.gecko = true;
}
3.16. 3.15

//
var is={ie:navigator.appName=='Microsoft Internet Explorer',java:
navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:
navigator.userAgent.toLowerCase(),version:parseFloat(
navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:
navigator.platform=='Win32'} is.mac=is.ua.indexOf('mac')>=0;if(
is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}
, ,
.
, JSMin JavaScript.
.
, Packer,
JavaScript.

Packer
Packer JavaScript. ,
(Dean Edwards),
. , Packer
. ZIP- JavaScript.
- Packer : http://dean.edwards.name/packer/.
Packer , -
. (

58
),
( JSMin). .
3.17 , Packer.
3.17. , Packer

eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,
String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[(function(e){return
d[e]})];e=(function(){return'\\w+'});c=1};while(c--){if(k[c]){p=p.replace(new
RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('u 1={5:2.f==\'t s
r\',h:2.j(),4:2.f==\'k\',3:2.l.m(),n:7(2.d.o(p))||7(2.d),q:2.g==\'i\'}1.
b=1.3.6(\'b\')>=0;a(1.3.6(\'c\')>=0){1.5=1.4=9;1.c=e}a(1.3.6(\'8\')>=0){1.5=
1.4=9;1.8=e}',31,31,'|is|navigator|ua|ns|ie;.
, Packer,
. , , , 50%,
,
JavaScript.

JavaScript-
. , , ,
-.
,
, JavaScript Archive Network (JSAN).
Perl-,
CPAN (Comprehensive Perl Archive Network). JSAN
- http://openjsan.org/.
JSAN ,
- ,
. , JSAN , ,
JSAN.
, ,
. , JSAN,

DOM.Insert,

http://openjsan.org/doc/r/rk/rkinyon/DOM/Insert/0.02/lib/DOM/Insert.html.
HTML -. ,
-, JSAN,
3.18.
Listing 3-18. JSAN (DOM.Insert)

// , JSAN
try {

59
// JSAN
JSAN.use( 'Class' )
JSAN.use( 'DOM.Utils' )
// JSAN ,
} catch (e) {
throw "DOM.Insert requires JSAN to be loaded";
}
// DOM
if ( typeof DOM == 'undefined' )
DOM = {};
// DOM.Insert,
// 'Object'
DOM.Insert = Class.create( 'DOM.Insert', Object, {
// ,
initialize: function(element, content) {
// , HTML
this.element = $(element);
// HTML
this.content = content;
// HTML ,
// Internet Explorer
if (this.adjacency && this.element.insertAdjacentHTML) {
this.element.insertAdjacentHTML(this.adjacency, this.content);
// , ,
// W3C
} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.fragment =
this.range.createContextualFragment(this.content);
this.insertContent();
}
}
});
- JavaScript,
, .
JavaScript. JavaScript
, ,
.

60
,
. - , ,
,
. ,
JavaScript, . ,
, ,
.

61

4
, ,
. ,
, ,

. , JavaScript
: -
( C#, PHP, Perl, Python Java).
.
,
JavaScript, .
(, ) .
JavaScript .
, JavaScript,
, ,
, .

. ,
, . .
, ,


,
. ,
. ,
, (
) .

Internet Explorer

. , Internet Explorer .
, , ,
Internet Explorer (-
, , JavaScript- ).
, Internet Explorer
:

; ,
, .

, .
.

, , , ..
, .
, .

62
, Internet Explorer, . 4.1.

. 4.1. JavaScript Internet Explorer


, JavaScript
( Internet Explorer). ,
, , , Internet
Explorer.

Firefox
- Firefox ,
- -.
JavaScript , . Firefox
:

JavaScript. ,
.

, , ,
.

JavaScript
, .
- ,
.

, , ,
, .. .
( Firebug, , .)
Firefox . 4.2. ,

, .

63

. 4.2. JavaScript Firefox


Firefox , .
Firefox.
.

Safari
Safari , .
JavaScript ( , )
. - JavaScript .
, . ,
.
( JavaScript)
, 4.1 ( Safari).
4.1. , Safari

defaults write com.apple.Safari IncludeDebugMenu 1


Safari ,
JavaScript.
, .
:

,
, Internet Explorer.

, , .

64

, ,
, .
, Safari 2.0, . 4.3.

. 4.3. JavaScript Safari


Safari , -.
WebKit ( Safari )
, .
.

Opera
, , Opera.
, Opera ,
. ,
Firefox, :

, .

, , .

(, JavaScript, CSS ..).


, JavaScript, ,

. - . .
4.4 Opera 9.0.

65

. 4.4. JavaScript Opera


Opera - .

, -.
JavaScript ,
, .

DOM
DOM , ,
-. -,
, , .

DOM-

-,

, , .
, , .

DOM, Firefox
Firefox DOM- ,
Firefox ( ).
HTML-.
. 4.5.

66

. 4.5. Firefox DOM-


HTML-,
, , . ,
- . .

DOM-, Safari
Safari DOM-, .
DOM-, Firefox,
.
DOM- Safari . 4.6.

67

. 4.6. DOM-, Safari


Safari, ,
JavaScript. , Safari
, , . ,
DOM- , 4.2.
4.2. Enabling the Safari DOM Inspector

defaults write com.apple.Safari WebKitDeveloperExtras -bool true


Safari DOM- ,
, , .
Firefox, Safari
.


, , - DOM-.
Firefox, View Rendered Source[1] ( ),
, View Source (
), HTML-,

68
.
-: http://jennifermadden.com/scripts/ViewRenderedSource.html.
, ,
, ,
, (. . 4.7).

. 4.7. View Rendered Source, Firefox


View Rendered Source ; , View Source
( ), Firefox DOM.

Firebug
Firebug ,
JavaScript. , (Joe Hewitt),
JavaScript-. , DOM-.

http://www.joehewitt.com/software/firebug/.

-:

69
,
. ,
JavaScript , .
, ,
, , , .
. 4.8.

. 4.8. Firebug
, Firebug.

Firefox

Firebug

JavaScript.

Venkman
, JavaScript,
Venkman. Mozilla, Venkman
JavaScript, Mozilla.
Firefox -:

Mozilla Venkman: http://www.mozilla.org/projects/venkman/

Venkman Firefox: https://addons.mozilla.org/firefox/216/

Venkman: http://www.mozilla.org/projects/venkman/venkman-walkthrough.html
Firebug ,

JavaScript,

, . Venkman
Firefox . 4.9.

70

. 4.9. Venkman JavaScript debugger, Firefox


, ,
, ,
,
.

.
,
, - , ,
, .
,
, , ,
, .
,
JavaScript,
.

JSUnit
JSUnit -
JavaScript. JUnit Java,
, , JUnit Java.

71

http://www.jsunit.net/,

(http://www.jsunit.net/documentation/).
( ,
), :

.
,
.
: ( -).
: , true/false,
,
. ,
, .
,
.
4.3, 4.4.
4.3. , JSUnit

<html>
<head>
<title>JsUnit Test Suite</title>
<script src="../app/jsUnitCore.js"></script>
<script>
function suite() {
var newsuite = new top.jsUnitTestSuite();
newsuite.addTestPage("jsUnitTests.html");
return newsuite;
}
</script>
</head>
<body></body>
</html>
4.4. ,
JSUnit

<html>
<head>
<title>JsUnit Assertion Tests</title>
<script src="../app/jsUnitCore.js"></script>
<script>
// (true)
function testAssertTrue() {
assertTrue("true should be true", true);

72
assertTrue(true);
}
// (false)
function testAssertFalse() {
assertFalse("false should be false", false);
assertFalse(false);
}
//
function testAssertEquals() {
assertEquals("1 should equal 1", 1, 1);
assertEquals(1, 1);
}
//
function testAssertNotEquals() {
assertNotEquals("1 should not equal 2", 1, 2);
assertNotEquals(1, 2);
}
// (null)
function testAssertNull() {
assertNull("null should be null", null);
assertNull(null);
}
// (null)
function testAssertNotNull() {
assertNotNull("1 should not be null", 1);
assertNotNull(1);
}
// - ;
</script>
</head>
<body></body>
</html>

JSUnit ,
, , , .

J3Unit
J3Unit JavaScript. JSUnit ,
, , JUnit
Jetty. Java-,
, . ,
Java, J3Unit ,

73
, . J3Unit
-, : http://j3unit.sourceforge.net/.

, , J3Unit
. , ,
, ,
4.5.
4.5. , J3Unit

<html>
<head>
<title>Sample Test</title>
<script src="js/unittest.js" type="text/javascript"></script>
<script src="js/suiterunner.js" type="text/javascript"></script>
</head>
<body>
<p id="title">Sample Test</p>
<script type="text/javascript">
new Test.Unit.Runner({
//
testToggle: function() {with(this) {
var title = document.getElementById("title");
title.style.display = 'none';
assertNotVisible(title, "title should be invisible");
element.style.display = 'block';
assertVisible(title, "title should be visible");
}},
//
testAppend: function() {with(this) {
var title = document.getElementById("title");
var p = document.createElement("p");
title.appendChild( p );
assertNotNull( title.lastChild );
assertEqual( title.lastChild, p );
}}
});
</script>
</body>
</html>
J3Unit ,
. - , .

Test.Simple

74
JavaScript . Test.Simple
JSAN

JavaScript.

Test.Simple

, ,
.
Test.Simple ( Test.More) :

Test.Simple: http://openjsan.org/doc/t/th/theory/Test/Simple/

Test.Simple: http://openjsan.org/doc/t/th/theory/Test/Simple/0.21/lib/Test/Simple.html

Test.More: http://openjsan.org/doc/t/th/theory/Test/Simple/0.21/lib/Test/More.html
Test.Simple

, . Test.Simple
4.6.
4.6. Test.Simple Test.More

//

Test More ( !)

new JSAN('../lib').use('Test.More');
// ( )
plan({tests: 6});
//
ok( 2 == 2, 'two is two is two is two' );
is( "foo", "foo", 'foo is foo' );
isnt( "foo", "bar", 'foo isnt bar');
//
like("fooble", /^foo/, 'foo is like fooble');
like("FooBle", /foo/i, 'foo is like FooBle');
like("/usr/local/", '^\/usr\/local', 'regexes with slashes in like' );
Test.Simple Test.More,
. ,
, ,
.

,
, JavaScript,

. ,
. ,
JavaScript.

75
[1] View Source Chart (. )

76

5
, -,
DOM (Document Object Model) , ,
, -
.
DOM JavaScript (
, JavaScript,
) ,
, , .
, DOM- ,
, .
, DOM,
DOM- HTML-.
JavaScript, -.

-.
, DOM. ,
, , . ,
DOM, , ,
, , -.


DOM XML- (
W3C). , , , ,
, , ( Java, Perl, PHP, Ruby, Python JavaScript). DOM
XML-.
XML, , HTML- (
XML) DOM-.

DOM
DOM XML, ,
. (, ,
..). , XML-
( document), .
,
.
XML, DOM .
DOM . , , ,
. , , , DOM,
, .
DOM-, HTML-:

<p><strong>Hello</strong> how are you doing?</p>

77
DOM-,

(,

).

, , . 5.1.
( ,
) .

. 5.1.
DOM- ,
. DOM.
. 5.2. . , DOM,
DOM- ( null, ).

78

. 5.2. DOM
,
. , , HTML-,
5.1.
5.1. - HTML, XML-

<html>
<head>
<title> DOM</title>
</head>
<body>
<h1> DOM</h1>
<p class="test"> , DOM ,
:</p>
<ul>
<li id="everywhere"> .</li>
<li class="test"> .</li>
<li class="test"> , ,
.</li>
</ul>
</body>
</html>
<html>. JavaScript
:

document.documentElement

79
, , ,
DOM-.

. , <h1>,
:

// !
document.documentElement.firstChild.nextSibling.firstChild
: DOM
, . , <h1>,
<title>. ?
XML: . , ,
<html> <head> ,
, , , <head>-.
:

HTML-
DOM .

DOM-
.

, ,
.
: ?

! ,
DOM.

DOM
HTML-. <h1>
, .
- , , ,

<h1>?

.nextSibling.nextSibling, <h1> <p>.


. , 5.2,
. DOM- ,
, .
HTML,
. , ,
HTML- .
5.2. XML-

function cleanWhitespace( element ) {


// element , HTML-
element = element || document;
//
var cur = element.firstChild;
// ,
while ( cur != null ) {

80
// , ,
//
if ( cur.nodeType == 3 && ! /\S/.test(cur.nodeValue) ) {
//
element.removeChild( cur );
//
} else if ( cur.nodeType == 1 ) {
//
cleanWhitespace( cur );
}
cur = cur.nextSibling; //
}
}
,
<h1>. , , :

cleanWhitespace();
// H1
document.documentElement
.firstChild

// Head

.nextSibling

// <body>

.firstChild

// H1

.nextSibling

//

. ,
- DOM-.
, DOM- ,
, .
, -.
HTML, DOM,
, .
.
nodeType .
, :

(nodeType = 1): XML-. ,


<li>,<a>, <p> <body> nodeType 1.

(nodeType = 3): .
DOM- previousSibling nextSibling
, .

(nodeType = 9): . , HTML <html>.

81
DOM (
, IE). ,
1, 3 9, document.ELEMENT_NODE, document.TEXT_NODE
document.DOCUMENT_NODE. DOM
, DOM-.

DOM-
DOM- ( )
, HTML DOM-.
, - DOM, . ,
previousSibling, nextSibling, firstChild, lastChild parentNode.
5.3 , , , null,
, previousSibling.
5.3. ,

function prev( elem ) {


do {
elem = elem.previousSibling;
} while ( elem && elem.nodeType != 1 );
return elem;
}
5.4 , , , null,
, nextSibling.
5.4.

function next( elem ) {


do {
elem = elem.nextSibling;
} while ( elem && elem.nodeType != 1 );
return elem;
}
5.5 , ,
firstChild.
5.5.

function first( elem ) {


elem = elem.firstChild;
return elem && elem.nodeType != 1 ?
next ( elem ) : elem;
}

82
5.6 , ,
lastChild.
5.6.

function last( elem ) {


elem = elem.lastChild;
return elem && elem.nodeType != 1 ?
prev ( elem ) : elem;
}
5.7 , ,
parentNode. ,
, parent(elem,2) parent(parent(elem)).
5.7.

function parent( elem, num ) {


num = num || 1;
for ( var i = 0; i < num; i++ )
if ( elem != null ) elem = elem.parentNode;
return elem;
}
, DOM-,
, . , ,
<h1>, , , :

// , <h1>
next( first( document.body ) )
, .

document.body. <body> body HTML


DOM-. ,
. , , ,
. , , :
<body>, , , ,
, . ,
, , , .

HTML-
Firefox Opera , HTMLElement,
HTML DOM-. ,
, , .

HTMLElement, HTML DOM-.
, , , :
1.

, ,
this, .

83
2.

, .

3.

HTMLElement,
HTML-, DOM.
, next , 5.8.
5.8. DOM- HTML DOM-

HTMLElement.prototype.next = function() {
var elem = this;
do {
elem = elem.nextSibling;
} while ( elem && elem.nodeType != 1 );
return elem;
};

next

) :

// <p>-
document.body.first().next()
. , ,
, JavaScript .
, jQuery
JavaScript (http://jquery.com), .

HTMLElement (Firefox, Safari Opera)


Internet Explorer .
, (Jason Karl Davis) (http://browserland.org),
HTMLElement ( ) ,

http://www.browserland.org/scripts/htmlelement/.

DOM
DOM , .
DOM
. , JavaScript DOM:
getElementById(everywhere): ,
, , ID everywhere. ,
.
getElementsByTagName(li): , ,
, li,
NodeList ( ).

84
, getElementById HTML-:
, id, .
XML- getElementById ( DOM
, JavaScript), id. ; XML , id, XML .

getElementsByTagName NodeList.
JavaScript, :
JavaScript .push(), .pop(), .shift() .. getElementsByTagName,
.

. ,
<h1>, :

document.getElementsByTagName("h1")[0]
, <h1>-,
. , <li>-
:

var li = document.getElementsByTagName("li");
for ( var j = 0; j < li.length; j++ ) {
li[j].style.border = "1px solid #000";
}
, , <li>-, ,
, ID:

document.getElementById("everywhere").style.fontWeight = 'bold';
, , , ID
, , ,
. ,
:

function id(name) {
return document.getElementById(name);
}
5.9. , HTML
DOM- . .
, , HTML-.
DOM-, .
5.9. HTML DOM-

function tag(name, elem) {


// ,
//

85
return (elem || document).getElementsByTagName(name);
}
,
<h1>. , :

// , <h1>
next( tag("h1")[0] );
,
DOM-. ,
DOM, DOM .

HTML DOM
HTML DOM- , , JavaScript
, DOM ,
. :

HTML.

HTML DOM.

.
, ,

HTML DOM. , ,
DOM. , .


,
DOM-. ,
, load window.
6. 5.10 DOM , ,
.
5.10.

addEvent,

window.onload

//
// ( addEvent, )
addEvent(window, "load", function() {
// HTML DOM-
next( id("everywhere") ).style.background = 'blue';
});
, .
,
. , , ..,
- , , , JavaScript.

86
DOM
, .
, , , DOM .
. , DOM
. , - ,
DOM.
, , DOM,
DOM-. ,
5.11.
5.11. DOM <script> ( )
HTML DOM

<html>
<head>
<title> DOM</title>
<script type="text/javascript">
function init() {
alert( "DOM !" );
tag("h1")[0].style.border = "4px solid black";
}
</script>
</head>
<body>
<h1> DOM</h1>
<!-- HTML -->
<script type="text/javascript">init();</script>
</body>
</html>
DOM ; ,
. , init,
DOM , . ,
: HTML ,
, DOM. ,
- , , .

DOM
, DOM, ,
, ( ), .
.
HTML DOM-
, . ,
, , HTML- :
1.

document: , DOM-. ,
, .

87
2.

document.getElementsByTagName document.getElementById: ,
getElementsByTagName getElementById;
.

3.

document.body: , ,
<body>. ,
, .
, ,

DOM ( ,
). .
, .
, , Firefox,
, , DOM
. , ,
.
domReady , , DOM
. , DOM , ,
. 5.12 ,
, DOM .
5.12. , DOM

function domReady( f ) {
// DOM ,
if ( domReady.done ) return f();
//
if ( domReady.timer ) {
//
domReady.ready.push( f );
} else {
// ,
// .
// addEvent.
addEvent( window, "load", isDOMReady );
//
domReady.ready = [ f ];
// DOM ,
domReady.timer = setInterval( isDOMReady, 13 );
}
}

// DOM
function isDOMReady() {
//
//

88
if ( domReady.done ) return false;
//
if ( document && document.getElementsByTagName &&
document.getElementById && document.body ) {
// ,
clearInterval( domReady.timer );
domReady.timer = null;
//
for ( var i = 0; i < domReady.ready.length; i++ )
domReady.ready[i]();
// ,
domReady.ready = null;
domReady.done = true;
}
}
, HTML-. domReady
, , addEvent ( 6),
.
domReady JavaScript, domready.js. 5.13
, domReady DOM.
5.13. domReady DOM

<html>
<head>
<title> DOM</title>
<script type="text/javascript" src="domready.js"></script>
<script type="text/javascript">
function tag(name, elem) {
// ,
//
return (elem || document).getElementsByTagName(name);
}
domReady(function() {
alert( "DOM !" );
tag("h1")[0].style.border = "4px solid black";
});
</script>
</head>
<body>
<h1> DOM</h1>
<!-- HTML -->

89
</body>
</html>
, DOM XML-,
HTML DOM-, : -
HTML-? ,
.

HTML
HTML- ,
XML-. , , HTML
XML; HTML- ,
.
JavaScript/HTML- :
CSS-. ,
DOM.

(Simon Willison) (http://simon.incutio.com) 2003


(Andrew Hayward) (http://www.mooncalf.me.uk).
: ( ) ,
. 5.14.
5.14. , ,

function hasClass(name,type) {
var r = [];
// (
// )
var re = new RegExp("(^|\\s)" + name + "(\\s|$)");
//
//
var e = document.getElementsByTagName(type || "*");
for ( var j = 0; j < e.length; j++ )
// ,
//
if ( re.test(e[j]) ) r.push( e[j] );
//
return r;
}

(, <li> <p>), .

90
, , , (*),
, , . , ,
HTML-. , test,
:

hasClass("test"")
<li>-, test,
:

hasClass("test","li")
, <li>, test,
:

hasClass("test","li")[0]
.
getElementById getElementsByTagName, ,
DOM .

CSS
-, HTML-: CSS-. CSS , CSS- .
CSS (1, 2 3) ,
. ,
CSS 2 3, ,
, . CSS,
W3C , :

CSS 1: http://www.w3.org/TR/REC-CSS1#basic-concepts/

CSS 2: http://www.w3.org/TR/REC-CSS2/selector.html

CSS 3: http://www.w3.org/TR/2005/WD-css3-selectors-20051215/
, , , ,

. .
, CSS 2 , CSS 3
, . ,
CSS-:
#main <div> p: ID main, ,
<div>-, , <p>-.
CSS 1.
div.items > p: <div>-, items,
<p>-. CSS 2.
div:not(.items): <div>-, items.
CSS 3.
, , CSS-,
( CSS-).

91
CSS-,
, CSS 1 CSS 3.
, - .

cssQuery
CSS 13 cssQuery,
(Dean Edwards) (dean.edwards.name). :
CSS-, cssQuery . ,
cssQuery , CSS-,
CSS 3, .

). ,
, , . :

// <p>, <div>-
cssQuery("div > p");
// <div>, <p> <form>-
cssQuery("div,p,form");
// <p> <div>-,
// <a>-,
var p = cssQuery("p,div");
cssQuery("a",p);
cssQuery .
- , getElementsByTagName.
, Google, :

// Google
var g = cssQuery("a[href^='google.com']");
for ( var i = 0; i < g.length; i++ ) {
g[i].style.border = "1px dashed red";
}
cssQuery - (Dean Edwards),
: http://dean.edwards.name/my/cssQuery/.

JavaScript; .
cssQuery, , JavaScript
.

jQuery
JavaScript,
. CSS- ,
cssQuery, cssQuery,

. CSS 13

XPath.

92
DOM . cssQuery, jQuery
.
jQuery CSS XPath:

// <div>-, 'links',
// <p>-
$("div.links[p]")
// <p> <div>-
$("p,div").find("*")
// , Google
$("a[@href^='google.com']:even")

jQuery,

-,

$().get( ),
cssQuery. -, ,
jQuery CSS DOM. , cssQuery
Google, :

// Google
$("a[@href^=google.com]").css("border","1px dashed red");
, ,
- jQuery: http://jquery.com/.

, cssQuery, jQuery
HTML-; XML-.
, XML, , XPath.

XPath
XPath XML-.
, , , DOM, -
XPath. XPath, , ,
CSS-. 5.1 CSS-
XPath-.
5.1. CSS 3 XPath

CSS 3

XPath

//*

<p>-

//p

p > *

//p/*

ID

#foo

//*[@id=foo]

.foo

//*[contains(@class,foo)]

*[title]

//*[@title]

<p>-

p > *:first-

//p/*[0]

93

child

<p>- , A

Not possible

//p[a]

p +

* //p/followingsibling::*[0]

, XPath-
( XPath 1.0),
, :

XPath 1.0: http://www.w3.org/TR/xpath/

XPath 2.0: http://www.w3.org/TR/xpath20/


- ,

OReilly XML in a Nutshell, (Elliotte Harold) (Scott Means)


(2004 .), Apress Beginning XSLT 2.0: From Novice to Professional,
(Jeni Tennison) (2005 .). ,
XPath:

W3Schools XPath Tutorial: http://w3schools.com/xpath/

ZVON XPath Tutorial: http://zvon.org/xxl/XPathTutorial/General/examples.html


XPath ; IE Mozilla

( ) XPath, Safari Opera .


XPath-, JavaScript. -
( ),
:

XML for Script: http://xmljs.sf.net/

Google AJAXSLT: http://goog-ajaxslt.sf.net/


, Sarissa (http://sarissa.sf.net/)

. ,
XML,
XML-. ,
XPath Opera Safari, XPath.
-

XPath

JavaScript.
, XPath ,
CSS-.
, , DOM, DOM-, , .
, DOM-.


DOM- : ,
. -, .
.

94
,
, , DOM, ,
. , , HTML DOM- XML DOM, , , . DOM-,
. 5.3, <p>-, <strong> .
<strong> .

. 5.3. DOM-, ,
, . <strong>,
, .
, innerText,
, Mozilla. .
, , XML
DOM-, .
, , ,
, , .
, strongElem <strong>. 5.15 ,
, DOM.
5.15. <strong>

95
// , Mozilla:
strongElem.innerText
// :
strongElem.firstChild.nodeValue
, , , ,
<p>.
,
, , 5.16. text()
,
.
5.16.

function text(e) {
var t = "";
// ,
// , ,
e = e.childNodes || e;
//
for ( var j = 0; j < e.length; j++ ) {
// ,
// ,
//
t += e[j].nodeType != 1 ?
e[j].nodeValue : text(e[j].childNodes);
}
//
return t;
}

,
, <p>, .
:

// <p>
text( pElem );
, HTML, XML DOM,

HTML,
, ,
HTML DOM-. , ,

96
Internet Explorer,
HTML DOM-: innerHTML. HTML ,
. , innerHTML ,
.
. innerHTML, , , ,
, , . ,
, , ,
innerHTML:

, Mozilla, innerHTML
<style>.

Internet Explorer ,
- .

innerHTML HTML DOM-;


XML DOM- .
innerHTML ; ,

HTML- . - ,
, . ,
, , . 5.3:

// HTML innerHTML <strong>


// "Hello"
strongElem.innerHTML
// HTML innerHTML <p>
// "<strong>Hello</strong> how are you doing?"
pElem.innerHTML
, , ,
, . ,
HTML- ,
, .
10.



. ,
, XML-
, HTML,
-:

<form name="myForm" action="/test.cgi" method="POST">


...
</form>
DOM formElem, HTML form ,
-.
:

97
formElem.attributes = {
name: "myForm",
action: "/test.cgi",
method: "POST"
};

, : - Safari s.
, hasAttribute Internet Explorer.
- ? 5.17,
getAttribute ( ) ,
.
5.17.

function hasAttribute( elem, name ) {


return elem.getAttribute(name) != null;
}
, , , ,
.


,
DOM-.
, XML DOM , getAttribute
setAttribute. :

//
id("everywhere").getAttribute("id")
//
tag("input")[0].setAttribute("value","Your Name");

getAttribute-setAttribute,

HTML

DOM-

, -.
DOM ( HTML DOM), .
, DOM DOM-
:

//
tag("input")[0].value
//
tag("div")[0].id = "main";
, .
.

98
,

className,

elem.className, getAttribute(class).
for, htmlFor.
CSS-: cssFloat cssText. - ,
, class, for, float text JavaScript .

, , .
5.18 .
, , attr(element, id), .
, , attr(element, class, test),
.
5.18.

function attr(elem, name, value) {


//
if ( !name || name.constructor != String ) return '';
// ,
//
name = { 'for': 'htmlFor', 'class': 'className' }[name] || name;
// ,
if ( typeof value != 'undefined' ) {
//
elem[name] = value;
// setAttribute
if ( elem.setAttribute )
elem.setAttribute(name,value);
}

//
return elem[name] || elem.getAttribute(name) || '';
}
, ,
. 5.19
attr .
5.19. attr DOM

// class <h1>-
attr( tag("h1")[0], "class", "header" );
// <input>
var input = tag("input");

99
for ( var i = 0; i < input.length; i++ ) {
attr( input[i], "value", "" );
}
// <input>, name
// 'invalid'
var input = tag("input");
for ( var i = 0; i < input.length; i++ ) {
if ( attr( input[i], "name" ) == 'invalid' ) {
input[i].style.border = "2px solid red";
}
}
DOM (, ID, class, name ..),
.

. , (
DOM- ) , , ,
. , , ,
. HTML
, 5.20.
5.20. HTML- ,

<html>
<head>
<title> </title>
<style>dd { display: none; }</style>
</head>
<body>
<h1> </h1>
<dl>
<dt></dt>
<dd>, .</dd>
<dt></dt>
<dd> .</dd>
<dt></dt>
<dd> .</dd>
</dl>
</body>
</html>
, , 6,
. ,
( ) .
. 5.21
, .
5.21. ,

100
// DOM
domReady(function(){
//
var dt = tag("dt");
for ( var i = 0; i < dt.length; i++ ) {
//
addEvent( dt[i], "click", function() {
// ,
var open = attr( this, "open" );
//
next( this ).style.display = open ? 'none' : 'block';
// ,
attr( this, "open", open ? '' : 'yes' );
});
}
});
, , DOM, ,
, DOM-, , ,
.

DOM
, DOM, , XML-
, ;
. DOM : ,
, , DOM,
.

DOM
, DOM, createElement,
.
DOM ( , DOM).
DOM-.
createElement , , DOM - .
, XSLT XHTML- ( XHTML, ), , XML,
XML. , ,
, HTML DOM-
(, XHTML DOM-).
, DOM- XHTML,
5.22.

101
5.22. DOM-

function create( elem ) {


return document.createElementNS ?
document.createElementNS( 'http://www.w3.org/1999/xhtml', elem ) :
document.createElement( elem );
}
, , , <div>-
:

var div = create("div");


div.className = "items";
div.id = "all";
, DOM-,

, createTextNode. , ,
, .
, DOM- , DOM, , .

DOM
DOM , DOM.
.
, insertBefore, .
:

.insertBefore( ,
);
, ,
: .
, .
, ( ,
) , :
?. appendChild,
. appendChild ,
. :

.appendChild( );
insertBefore
appendChild, ,
. 5.23 5.24,
(), ,

().

before

, . ,
(),

102
. , ( ,
null).
5.23.

function before( parent, before, elem ) {


// , (parent)
if ( elem == null ) {
elem = before;
before = parent;
parent = before.parentNode;
}
parent.insertBefore( checkElem( elem ), before );
}
5.24.

function append( parent, elem ) {


parent.appendChild( checkElem( elem ) );
}
, 5.25 ,
( ).
5.25. before append

function checkElem( elem ) {


// ,
return elem && elem.constructor == String ?
document.createTextNode( elem ) : elem;
}
, before append, DOM-, DOM
, (. 5.26).
5.26. append before

// <li>-
var li = create("li");
attr( li, "class", "new" );
// <li>
append( li, " , !" );
// <li>
before( first( tag("ol")[0] ), li );
// <ol>

103
<ol></ol>
// :
<ol>
<li class='new'> , !</li>
</ol>
DOM ( insertBefore, appendChild)

.
, .
, DOM-,
DOM - .

DOM HTML
HTML ,
DOM

DOM-.

innerHTML. , HTML, ,
HTML .
, <ol>, <li>.
, , :

// LI OL-
tag("ol")[0].innerHTML = "<li>.</li><li>.</li><li>.</li>";
, , DOM-

http://www.

quirksmode.org) , DOM. ,
,
innerHTML:

, innerHTML XML DOM-, ,


DOM- .

XHTML-, XSLT, ,
innerHTML, XML-.

innerHTML , , ,
,
DOM-, .
,

. -, DOM,
append before HTML- DOM. . checkElem,
5.27, HTML-, DOM- DOM-.
5.27. , DOM- HTML-
DOM-

function checkElem(a) {
var r = [];

104
// ,
if ( a.constructor != Array ) a = [ a ];
for ( var i = 0; i < a.length; i++ ) {
//
if ( a[i].constructor == String ) {
// HTML
var div = document.createElement("div");
// HTML, DOM-
div.innerHTML = a[i];
// DOM- DIV-
for ( var j = 0; j < div.childNodes.length; j++ )
r[r.length] = div.childNodes[j];
} else if ( a[i].length ) { //
// , DOM-
for ( var j = 0; j < a[i].length; j++ )
r[r.length] = a[i][j];
} else { // , , DOM-
r[r.length] = a[i];
}
}
return r;
}
, 5.28,
checkElem.
5.28. DOM

function before( parent, before, elem ) {


// , (parent)
if ( elem == null ) {
elem = before;
before = parent;
parent = before.parentNode;
}
//
var elems = checkElem( elem );
// ,
//
for ( var i = elems.length - 1; i >= 0; i-- ) {
parent.insertBefore( elems[i], before );
}
}

105
function append( parent, elem ) {
//
var elems = checkElem( elem );
//
for ( var i = 0; i <= elems.length; i++ ) {
parent.appendChild( elems[i] );
}
}

, , <li>
:

append( tag("ol")[0], "<li>.</li>" );


// HTML <ol>-
<ol>
<li>.</li>
<li>.</li>
<li>.</li>
</ol>
// :
<ol>
<li>.</li>
<li>.</li>
<li>.</li>
<li>.</li>
</ol>
// , before
before( last( tag("ol")[0] ), "<li>.</li>" );
// <ol> :
<ol>
<li>.</li>
<li>.</li>
<li>.</li>
<li>.</li>
</ol>

. , DOM? ,
.

DOM
DOM , . ,

106
, .
: removeChild. ,
appendChild, . :

.removeChild( );
, .
5.29.
5.29. DOM

// DOM
function remove( elem ) {
if ( elem ) elem.parentNode.removeChild( elem );
}
5.30 ,
DOM-.
5.30.

// DOM
function empty( elem ) {
while ( elem.firstChild )
remove( elem.firstChild );
}
, , <li>,
, , <li>,
. ,
JavaScript:

// <li> <ol>
remove( last( tag("ol")[0] ) )
// :
<ol>
<li> Javascript.</li>
<li>???</li>
<li> !</li>
</ol>
// :
<ol>
<li> Javascript.</li>
<li>???</li>
</ol>
// remove() empty()
empty( last( tag("ol")[0] ) )

107
// <ol>:
<ol></ol>
DOM, ,
, .

, . ,
, , DOM,

. , ,
-.
DOM- , ,
. ,
DOM- , - : http://jspro.org,
Source Code/Download - Apress: http://www.apress.com.
DOM-:
.

108

6
DOM-
. JavaScript -,
, , ,
.

, , . ,
, , -.
JavaScript HTML , , .
DOM , -.
JavaScript , ,
, . , ,
, ,
-.
JavaScript
, . ,
, .
DOM- , ,
-.

JavaScript
JavaScript, ,
, . JavaScript-,
( HTML DOM).
, , ,
-. DOM JavaScript
, -.


JavaScript . ,
. , -
, ,
.
, ,
, . ,
, , .

, , , , .
, JavaScript, , ,
.

JavaScript
JavaScript . ,
setTimeout( ), .

109
JavaScript , , - ,
6.1 . ,
. JavaScript ,
- . , .
6.1. JavaScript

// : !
// , ,
//
while ( ! window.loaded() ) { }
// ,
document.getElementById("body").style.border = "1px solid #000";
, , ,
window.loaded( ), . windows
loaded( ), , JavaScript. - ,
JavaScript ( , ).
JavaScript , -,
. 6.1. while , .
JavaScript - , (
, ).

. 6.1. , JavaScript
, while
, .
, .
: - , while ( JavaScript)
, , .



, , , JavaScript.
, DOM-, ,

110
, . ,
, , .
6.2. , .
, (window.onload)
JavaScript. window.onload( ) .
, , ,
submit.
6.2. JavaScript

//
window.onload = loaded;
// , .
function loaded() {
// ,
document.getElementById("body").style.border = "1px solid #000";
}
6.2 , 6.1, .
, ( loaded),
( onload). , ,
window.onload, . JavaScript . 6.2.
JavaScript
. ,
(loaded), , (window.onload).
, ,
, , ,
DOM.
, , .

. 6.2.

111
JavaScript , (capturing) ,
(bubbling). : (
, , ), ,
, , , .
. 6.3. ,
<a>- .

. 6.3.
( . 6.3),
. , <a>,
, document, , <body>,
, <div>, , <a>;
. , , ,
<li>, <ul>, <div>, <body> document.
,
, . . ,
<li>- ,
, .
, 6.3.
6.3.

// <li>
//
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
// <li> mouseover,

112
// <li> .
li[i].onmouseover = function() {
this.style.backgroundColor = 'blue';
};
// <li> ,
// <li>
li[i].onmouseout = function() {
this.style.backgroundColor = 'white';
};
}
:
<li>,

; ,

. , <li>,
. <li>
<a>, , <li>.
:

<li> mouseover: <li>.

<li> mouseout: <li> <a>, .

<a> mouseover: <a>.

<li> mouseover: mouseover, <a>, mouseover,


<li>.
, ,

, t.
onevent,
, .
.
:
mouseout <li> mouseover <a> <li>.
.
mouseout - ,
<li> . - , ,
( <a> <li>)
.
<a> mouseover <li>,
. <a>
, DOM ,
.

mouseover (, , ).

<li>,

113
, , <a>
mouseover? - , ?
.


JavaScript ,
.
, - ,
, , . ,
- .
.


,
- .
. ,
keyCode . ,
, .
: Internet Explorer ,
W3C. Internet Explorer (
window.event),

6.4.
<textarea>. textarea Enter,
. ?
.
6.4. DOM

// <textarea>,
//
document.getElementsByTagName("textarea")[0].onkeypress = function(e){
// ,
// ( IE)
e = e || window.event;
// Enter, false ( )
return e.keyCode != 13;
};
,
. ,
, , ,
.

this
this ( 2)

this

114
. ( )
;
. , 6.5, ,
, ,
, .
, this
, .
6.5. <li>

// <li>
//
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
li[i].onclick = handleClick;
}
//
//
function handleClick() {
this.style.backgroundColor = "blue";
this.style.color = "white";
}
this , , ,
, JavaScript. ,
, , .


, ,
. :
, ,
. , . 6.4,
<a> .

115

. 6.4. <a>
( ) .
, Internet Explorer , .
6.6.
: , .
: W3C-, , Internet
Explorer.
6.6.

function stopBubble(e) {
// , IE-
if ( e && e.stopPropagation )
// W3C- stopPropagation()
e.stopPropagation();
else
//
// , Internet Explorer
window.event.cancelBubble = true;
}
, , , ? ,
. ,
( , .
6.7 , ,
. mouseover
mouseout DOM-. ,
, ,
.

116
6.7. stopBubble()

// , DOM
var all = document.getElementsByTagName("*");
for ( var i = 0; i < all.length; i++ ) {
//
//
all[i].onmouseover = function(e) {
this.style.border = "1px solid red";
stopBubble( e );
};
//
//
all[i].onmouseout = function(e) {
this.style.border = "0px";
stopBubble( e );
};
}
, , ,
.
-. ,
, .


,
. , <a> -;
. . 6.5 , .
- <a>.
, , DOM : .
,
. , , /.

117

. 6.5.
,
. , ,
:

<a> URL, href.


Ctrl+S,
-.

HTML <form> URL


.

<img>, alt title (


) , .

, .
. ,
? , <a> , ?
, ,
, .
, : IE-, ,
W3C. 6.8. :
, .
, : return stopDefault( e ); false
( stopDefault).
6.8.

function stopDefault( e ) {
// (W3C)
if ( e && e.preventDefault )

118
e.preventDefault();
// IE
else
window.event.returnValue = false;
return false;
}
, stopDefault, ,
. 6.9,
. ,
<iframe>, .
, .

95%.
, - ,
( ), ,
, <iframe>;
- .
6.9. stopDefault()

// , Iframe,
// ID 'iframe'
var iframe = document.getElementById("iframe");
// <a>
var a = document.getElementsByTagName("a");
for ( var i = 0; i < a.length; i++ ) {
// <a>
a[i].onclick = function(e) {
// IFrame
iframe.src = this.href;
// -,
// <a> ( )
return stopDefault( e );
};
}
DOM ,
DOM-. , DOM-,
. , ;
, DOM-.
, , ,
.

119
JavaScript
.
,

HTML-. , (
, DOM).
Netscape Internet Explorer ,
, . Netscape ,
W3C, Internet Explorer .
.
, ,
. IE W3C .
, .


.
. ,
DOM-, . 6.10
.
6.10.

// <form>
// 'submit'
document.getElementsByTagName("form")[0].onsubmit = function(e){
//
return stopDefault( e );
};
// <body>
//
document.body.onkeypress = myKeyPressHandler;
//
window.onload = function(){ ; };
, .


,
.

this ,
( 6.5).

120

:

, .

.
window.onload
( ,
, ).
6.11, .

, Internet Explorer.
6.11. ,

//
window.onload = myFirstHandler;
// - , ,
// ,
// 'mySecondHandler'
window.onload = mySecondHandler;
, ,
, ,
, . ,
.

DOM-: W3C
, - DOM-
W3C. , Internet
Explorer, .
.
DOM- ( addEventListener), :
(, click), , ,
. 6.12 addEventListener.
6.12. ,
, W3C

// <form>
// 'submit'
document.getElementsByTagName("form")[0].
addEventListener('submit',function(e){
//
return stopDefault( e );
}, false);
// <body>
//

121
document.body.addEventListener('keypress', myKeyPressHandler, false);
//
window.addEventListener('load', function(){ ; }, false);

W3C-
, W3C, :

: .
addEventListener false ( ) true (
).

this .

,
.

W3C-
, W3C, :

Internet Explorer; attachEvent.


Internet Explorer , W3C,

,
. , W3C,
.

DOM-: IE
, Internet Explorer ,
W3C. , ,
. 6.13 Internet
Explorer.
6.13. , Internet
Explorer

// <form>
// 'submit'
document.getElementsByTagName("form")[0].attachEvent('onsubmit',function(){
//
return stopDefault();
},);
// <body>
//
document.body.attachEvent('onkeypress', myKeyPressHandler);
//
window.attachEvent('onload', function(){ ; });

122
IE-
, Internet Explorer, :

,
.

IE-
, Internet Explorer, :

Internet Explorer .

this window,
( IE).

window.event.

on , onclick click.

Internet Explorer. , IE,


W3C- addEventListener.
, Internet Explorer

. -
, .
: DOM ,
.

addEvent removeEvent
, - (Peter-Paul Koch) ( http://quirksmode.org)
2005 , , JavaScript,

addEvent

removeEvent,

DOM. ,
. , , (Dean
Edwards), , .
,
. ,
, (
this ). 6.14 ,
, addEvent,
, ,
this.
6.14. , addEvent

//
addEvent( window, "load", function(){
//
addEvent( document.body, "keypress", function(e){
// + Ctrl
if ( e.keyCode == 32 && e.ctrlKey ) {

123
//
this.getElementsByTagName("form")[0].style.display = 'block';
//
e.preventDefault();
}
});
});
addEvent DOM. , ,
. ,
, , this
, 6.15.
6.15. addEvent/removeEvent,

// addEvent/removeEvent written by Dean Edwards, 2005


// with input from Tino Zijdel
// http://dean.edwards.name/weblog/2005/10/add-event/
function addEvent(element, type, handler) {
// ID
if (!handler.$$guid) handler.$$guid = addEvent.guid++;
// -
if (!element.events) element.events = {};
// -
// -
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
//
// ( )
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// -
handlers[handler.$$guid] = handler;
//
//
element["on" + type] = handleEvent;
};

124
// , ID
addEvent.guid = 1;
function removeEvent(element, type, handler) {
// -
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
};
function handleEvent(event) {
var returnValue = true;
// (IE )
event = event || fixEvent(window.event);
// -
var handlers = this.events[event.type];
//
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};
// IE ""
function fixEvent(event) {
// W3C
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
};

addEvent

125
addEvent
:

, , .

this , .

, .

addEvent
addEvent :

(
).
addEvent removeEvent, ,

. C ,
, ,
, , , ,
.


JavaScript .
, , ,
.
, -.
.
, : : ,
(mouseover, mouseout), ,
(mouseup, mousedown, click).
, : ,
,
form . ,
, : keyup, keydown keypress.
, : ,
. , , ,
.
: focus blur ( , ).
: ,
. submit ;
change ; select
, <select>.
: ,
.
( load), , ( unload beforeunload).

126
error JavaScript,
.
,
, ,
, , ,
.

DOM-
, :

JavaScript,

. , ,
,
, , (
) .
, ,
:
1.

. , HTML
DOM, ,
(, if ( document && document.getElementById ) ).
2.

2.

DOM .
, DOM-, ,
.

3.

, , , DOM
addEvent. - - ,
<a href="#" onclick="doStuff();">;</a>.
, , JavaScript ,
, .
URL, , ,
.
,

JavaScript, . , -
JavaScript, - ?
CSS, - ? , ,
- ? . , , -
JavaScript, ,
.

JavaScript
HTML-
. , ,
:

127

JavaScript ( ) ,
-? href="" href="#",

JavaScript-.

JavaScript, ?

<select> ( JavaScript).
, , -,

, JavaScript,
.

JavaScript
, ,
. Google Google
Accelerator, , ,
,
. , ( )
, , ( JavaScript).
Google Accelerator ,
.
, http-,
. GET-
; POST- .
, GET- (
), Google Accelerator .
- , Google, , .
, - .
, , ,
, , .

CSS
,
, JavaScript, CSS.
DHTML , ( display,
none, visibility, hidden),
( JavaScript) .
JavaScript, .
6.16.
6.16.

JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

128
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<!-- <html>
, , JavaScript.-->
<script>document.documentElement.className = "js";</script>
<!-- JavaScript ,
.-->
<style>.js #fadein { display: none }</style>
</head>
<body>
<div id="fadein"> , ;</div>
</body>
</html>
DHTML-. ,
JavaScript, , -.


, - -
. ,
: ( ), ,
. (- , , ,
, . .)
JavaScript , , click, mouseover
mouseout, , .
, , :
(click): ,
Enter.
- . ,
,
submit, , -.
, submit,
.
(mouseover): -
.
mouseover, focus,
, , , .
(mouseout): focus
mouseover, blur , . blur
, mouseout .
, , ,
6.3, , , (.
6.17).

129
6.17.

// <a>,
var li = document.getElementsByTagName("a");
for ( var i = 0; i < a.length; i++ ) {
// mouseover focus <a>,
// <a> ,
// ,
// ( )
a[i].onmouseover = a[i].onfocus = function() {
this.style.backgroundColor = 'blue';
};

// mouseout blur <a>,


// <a> ,
//
a[i].onmouseout = a[i].onblur = function() {
this.style.backgroundColor = 'white';
};
}

.
, , -,
.

, DOM, DOM-
, JavaScript,
.
JavaScript
. , ,
. DOM-,
. ,
-.
, ,
.

130

7 JavaScript CSS
JavaScript CSS JavaScript-.
- -
. ,
.
, 6,
.

-, -
,

JavaScript , ,
, .


JavaScript CSS .
, .
CSS,
style. , , :
elem.style.height. ,
: elem.style.height = '100px'.
CSS DOM- ,
. -, JavaScript , ,
, ( ). ,
, , style
( , 100px 100).
-, 100 ,
, , style 100px. ,
, CSS
style .
CSS JavaScript :
, , , .
, , ,
, DOM-.
( W3C- IE- )
.
JavaScript.
,
.
,
. , Internet Explorer
,
, W3C.

131
7.1,
7.2.
7.1. CSS Style

// style (name) (elem)


function getStyle( elem, name ) {
// style[], ,
// ( )
if (elem.style[name])
return elem.style[name];
// , IE
else if (elem.currentStyle)
return elem.currentStyle[name];
// W3C,
else if (document.defaultView && document.defaultView.getComputedStyle) {
// textAlign
// 'text-align'
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();
// style
// ( )
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
// , -
} else
return null;
}
7.2. , CSS-
, style

<html>
<head>
<style>p { height: 100px; }</style>
<script>
window.onload = function(){
//
var p = document.getElementsByTagName("p")[0];
//
alert( p.style.height + " null" );

132
//
alert( getStyle( p, "height" ) + " 100px" );
};
</script>
</head>
<body>
<p> 100 .</p>
</body>
</html>
7.2 , CSS- DOM. ,
CSS . ,
( , , ).
, .
, , ,
DHTML.


, JavaScript CSS
( ,
, ).
: ,
.
.


-
. CSS-
(
, ).
,
, CSS. CSS
.
. , CSS, . 7.1.

133

. 7.1. - CSS
( )
( ). - ,
, . CSS,
. ,
HTML -, 7.3.
7.3.

HTML

-,

<html>
<head>
<style>
p{
border: 3px solid red;
padding: 10px;
width: 400px;
background: #FFF;
}
p.odd {
/* */
position: static;
top: 0px;
left: 0px;
}
</style>
</head>
<body>

134
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam ;p>
<p class='odd'>Phasellus dictum dignissim justo. Duis nec risus id
nunc;p>
<p>Sed vel leo. Nulla iaculis, tortor non laoreet dictum, turpis diam
;</p>
</body>
</html>
,

HTML-,

-:
: ;

top

left

. . 7.2 ,
CSS-: position: static; top: 0px; left: 0px;.

135
. 7.2. ()

, ,
- . top left
() . CSS position:
relative; top: -50px; left: 50px; . 7.3.

7.3.

,
:
.
, .

CSS position: absolute; top: 20px; left: 0px; . 7.4.

136

. 7.4. ,
, ,
:
. top left 0

,
. CSS position: fixed; top: 20px;
right: 0px; . 7.5.
, , ,
DOM-,
.
, , ,
, CSS- .

137

. 7.5. ,
,


CSS- ,
. CSS-
, .
.
.
, , :
offsetParent:

. , offsetParent
( , Firefox , Opera
).
offsetLeft offsetTop:
offsetParent. , .

, 7.4,
DOM offsetParent,
.
7.4.

// X ( )
function pageX(elem) {
//
return elem.offsetParent ?

(x

y)

138
// ,
//
elem.offsetLeft + pageX( elem.offsetParent ) :
// ,
elem.offsetLeft;
}
// Y ( )
function pageY(elem) {
//
return elem.offsetParent ?
// ,
//
elem.offsetTop + pageY( elem.offsetParent ) :
// ,
elem.offsetTop;
}

. ,
style.left style.top,
, JavaScript CSS.
DOM
, . , ,
.
,
offsetParent.
,
pageX pageY. , 7.5,
offsetParent, ;
DOM, pageX pageY
.
7.5.

//
function parentX(elem) {
// offsetParent ,
//
return elem.parentNode == elem.offsetParent ?
elem.offsetLeft :
//
//

139
pageX( elem ) -pageX( elem.parentNode );
}
//
function parentY(elem) {
// offsetParent ,
//
return elem.parentNode == elem.offsetParent ?
elem.offsetTop :
//
//
pageY( elem ) -pageY( elem.parentNode );
}

CSS-. ,

). ,
getStyle CSS-,
.
, 7.6,
. getStyle,
( , , )
( , 100px 100).
7.6. CSS-

//
function posX(elem) {
// style
return parseInt( getStyle( elem, "left" ) );
}
//
function posY(elem) {
// style
return parseInt( getStyle( elem, "top" ) );
}


, .
(, ,
), .

CSS-. , left
top, ( bottom right).

140
, 7.7,
.
7.7. x y ,

//
function setX(elem, pos) {
// CSS- 'left' ,
//
elem.style.left = pos + "px";
}
//
function setY(elem, pos) {
// CSS- 'top' ,
//
elem.style.top = pos + "px";
}
, ,
7.8,
, 5 .
, DHTML-.
7.8.

// .
function addX(elem,pos) {
//
// .
setX( posX(elem) + pos );
}
// .
function addY(elem,pos) {
//
// .
setY( posY(elem) + pos );
}

. , ,
, .
, , .


,
, , .

getStyle (. 7.9).

141
7.9. DOM-

// ( CSS)
function getHeight( elem ) {
// CSS
//
return parseInt( getStyle( elem, 'height' ) );
}
// ( CSS)
function getWidth( elem ) {
// CSS
//
return parseInt( getStyle( elem, 'width' ) );
}
: ,
, ( , 0 ,
), ,
, , display none.
. (
display none) 0 ,
.
7.10 , ,
.
clientWidth clientHeight,
.
7.10. ,

// (
// )
function fullHeight( elem ) {
// ,
// offsetHeight , getHeight()
if ( getStyle( elem, 'display' ) != 'none' )
return elem.offsetHeight || getHeight( elem );
// ,
// display none,
// CSS-,
//
var old = resetCSS( elem, {
display: '',
visibility: 'hidden',
position: 'absolute'
});

142
// , clientHeight,
// , getHeight
var h = elem.clientHeight || getHeight( elem );
// CSS-
restoreCSS( elem, old );
//
return h;
}
// (
// )
function fullWidth( elem ) {
// ,
// offsetWidth , getWidth()
if ( getStyle( elem, 'display' ) != 'none' )
return elem.offsetWidth || getWidth( elem );
// ,
// display none,
// CSS-,
//
var old = resetCSS( elem, {
display: '',
visibility: 'hidden',
position: 'absolute'
});

// , clientWidth,
// , getWidth
var w = elem.clientWidth || getWidth( elem );
// CSS-
restoreCSS( elem, old );
//
return w;
}
// , CSS-,
//
function resetCSS( elem, prop ) {
var old = {};
//

143
for ( var i in prop ) {
//
old[ i ] = elem.style[ i ];
//
elem.style[ i ] = prop[i];
}
// restoreCSS
return old;
}
// resetCSS
function restoreCSS( elem, prop ) {
//
for ( var i in prop )
elem.style[ i ] = prop[ i ];
}
, ,
, .
,
.


, JavaScript
, . ,
,
.
CSS
, , ,
, :

visibility ,
. visibility : visible ( )
hidden ( ). , ,
<b>, visibility hidden,
, , . ,
:

// :
Hello John, how are you today?
// 'John' visibility: hidden
Hello

, how are you today?

display
. inline ( , <b> <span>

144
, ), block
( , <p> <div> , , ),
none ( ).
display , ,
, .
display :

// :
Hello John, how are you today?
// 'John' display: none
Hello, how are you today?

visibility

display

. , visibility hidden
, .
7.11 ,
display.
7.11. CSS-
display

// ( display)
function hide( elem ) {
// display
var curDisplay = getStyle( elem, 'display' );
// display
if ( curDisplay != 'none' )
elem.$oldDisplay = curDisplay;
// display none ( )
elem.style.display = 'none';
}
// ( display)
function show( elem ) {
// display ,
// ,
// 'block',
//
elem.style.display = elem.$oldDisplay || '';
}
opacity.
, ,
. ,
50% , , . -, ,
, Internet Explorer ( IE 5.5),
W3C- . ,

145
, 7.12. 0
, , 100 .
7.12. ,

//
// ( 0-100)
function setOpacity( elem, level ) {
// - , ,
// IE, Alpha
if ( elem.filters )
elem.style.filters = 'alpha(opacity=' + level + ')';
// W3C- opacity
else
elem.style.opacity = level / 100;
}
, ,
, ,
.

, , DHTML-,
-: .

, , .
,
DHTML-.

, (
display, none) ,
show(), , , .
7.13 , show() ,
.
7.13.

function slideDown( elem ) {


// 0
elem.style.height = '0px';
// ( , 0)
show( elem );
// ,
var h = fullHeight( elem );

146
// ,
// 20 ''
for ( var i = 0; i <= 100; i += 5 ) {
// , ,
// 'i',
(function(){
var pos = i;
//
//
setTimeout(function(){
//
elem.style.height = ( pos / 100 ) * h ) + "px";
}, ( pos + 1 ) * 10);
})();
}
}

, , ,
setOpacity( ), .
( 7.14) ,
0 ( ) 100% ( ).
, 7.13,
.
7.14. ,

function fadeIn( elem ) {


// 0
setOpacity( elem, 0 );
// ( ,
// 0)
show( elem );
// ,
// 20 ''
for ( var i = 0; i <= 100; i += 5 ) {
// , ,
// 'i',
(function(){
var pos = i;
//
//
setTimeout(function(){

147
//
setOpacity( elem, pos );
}, ( pos + 1 ) * 10);
})();
}
}
, 9.

DOM-, ,
, -.
,
.



,
JavaScript CSS.
, x y
- (. 7.15).
, , ,
MouseMove MouseDown ( ).
7.15.

//
function getX(e) {
//
e = e || window.event;
// , IE,
// IE
return e.pageX || e.clientX + document.body.scrollLeft;
}
//
function getY(e) {
//
e = e || window.event;
// , IE,
// IE
return e.pageY || e.clientY + document.body.scrollTop;
}

148
, , x
y, , . 7.16
, .
7.16. ,

// X- ,
// 'e'
function getElementX( e ) {
//
return ( e && e.layerX ) || window.event.offsetX;
}
// Y- ,
// 'e'
function getElementY( e ) {
//
return ( e && e.layerY ) || window.event.offsetY;
}
,
. , , ,
6 , .


, .
: , .

( , , - ).


, -.
, (
). 7.17
, scrollWidth scrollHeight,
, .
7.17. , -

// -
// ( )
function pageHeight() {
return document.body.scrollHeight;
}
// -
function pageWidth() {
return document.body.scrollWidth;

149
}


, (, ,
). (

7.18)

, ,
.
7.18. , ,

//
function scrollX() {
// Internet Explorer 6
// (strict)
var de = document.documentElement;
// pageXOffset,
return self.pageXOffset ||
//
//
( de && de.scrollLeft ) ||
// , body
document.body.scrollLeft;
}
//
function scrollY() {
// Internet Explorer 6
// (strict)
var de = document.documentElement;
// pageYOffset,
return self.pageYOffset ||
//
//
( de && de.scrollTop ) ||
// , body
document.body.scrollTop;
}

150
, ,
scrollTo,
.
scrollTo window ( ,
<iframe>) , x y,

<iframe>).

7.19

scrollTo.
7.19. scrollTo

// ,
// :
window.scrollTo(0,0);
// ,
// :
window.scrollTo( 0, pageY( document.getElementById("body") ) );


, , :
. ,
, .
, 7.20.
7.20. ,

//
function windowHeight() {
// Internet Explorer 6
// (strict)
var de = document.documentElement;

// innerHeight,
return self.innerHeight ||
//
( de && de.clientHeight ) ||
// , body
document.body.clientHeight;
}
//
function windowWidth() {
// Internet Explorer 6
// (strict)

151
var de = document.documentElement;
// innerWidth,
return self.innerWidth ||
//
( de && de.clientWidth ) ||
// , body
document.body.clientWidth;
}
. -,
, Gmail Campfire, ,
(Gmail , Campfire
). 11 ,
- .

,
. , (
, , ),
, .
, DOM-Drag,
(Aaron Boodman) (http://boring.youngpup.net/2001/domdrag).
, :
: ,
, . ,
.

, , ,
.
:
( , ).
.
: CSS,
x/y.
x y:
( ).
DOM-Drag .
( ),
. DOM-Drag
7.21.

152
7.21. DOM-Drag

<html>
<head>
<title>DOM-Drag </title>
<script src="domdrag.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function(){
// DOM-Drag, ,
// ID 'window',
Drag.init( document.getElementById("window") );
};
</script>
<style>
#window {
border: 1px solid #DDD;
border-top: 15px solid #DDD;
width: 250px;
height: 250px;
}
</style>
</head>
<body>
<h1>Draggable Window Demo</h1>
<div id="window"> ,
!</div>
</body>
</html>
DOM-Drag 7.22.
,
.
7.22. DOM-Drag

varDrag = {
//
obj: null,
//
// o = ,
// oRoot = , ,
// .
// minX, maxX, minY, maxY = ,
//
// bSwapHorzRef =
// bSwapVertRef =
// fxMapper, fyMapper = x y
//

153
init: function(o, oRoot, minX, maxX, minY,
maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper) {
//
o.onmousedown = Drag.start;
//
o.hmode = bSwapHorzRef ? false : true ;
o.vmode = bSwapVertRef ? false : true ;
// ,
o.root = oRoot && oRoot != null ? oRoot : o ;
//
if (o.hmode && isNaN(parseInt(o.root.style.left )))
o.root.style.left = "0px";
if (o.vmode && isNaN(parseInt(o.root.style.top )))
o.root.style.top = "0px";
if (!o.hmode && isNaN(parseInt(o.root.style.right )))
o.root.style.right = "0px";
if (!o.vmode && isNaN(parseInt(o.root.style.bottom)))
o.root.style.bottom = "0px";
//
// x y
o.minX = typeof minX != 'undefined' ? minX : null;
o.minY = typeof minY != 'undefined' ? minY : null;
o.maxX = typeof maxX != 'undefined' ? maxX : null;
o.maxY = typeof maxY != 'undefined' ? maxY : null;
//
// x y
o.xMapper = fXMapper ? fXMapper : null;
o.yMapper = fYMapper ? fYMapper : null;
// ,
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function();
o.root.onDrag = new Function();
},
start: function(e) {
//
var o = Drag.obj = this;
//
e = Drag.fixE(e);

154
// x y
var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
// x y
o.root.onDragStart(x, y);
//
o.lastMouseX = e.clientX;
o.lastMouseY = e.clientY;
// CSS
if (o.hmode) {
// min max ,
if (o.minX != null) o.minMouseX = e.clientX -x + o.minX;
if (o.maxX != null) o.maxMouseX = o.minMouseX + o.maxX -o.minX;
//
//
} else {
if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
}
// CSS
if (o.vmode) {
// min max ,
if (o.minY != null) o.minMouseY = e.clientY -y + o.minY;
if (o.maxY != null) o.maxMouseY = o.minMouseY + o.maxY -o.minY;
//
//
} else {
if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
}
//
//
document.onmousemove = Drag.drag;
document.onmouseup = Drag.end;
return false;
},
// ,
//
drag: function(e) {

155
//
e = Drag.fixE(e);
//
var o = Drag.obj;
//
var ey = e.clientY;
var ex = e.clientX;
// x y
var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
var nx, ny;
// X, ,
//
if (o.minX != null) ex = o.hmode ?
Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
// X, ,
//
if (o.maxX != null) ex = o.hmode ?
Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
// Y, ,
//
if (o.minY != null) ey = o.vmode ?
Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
// Y, ,
//
if (o.maxY != null) ey = o.vmode ?
Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);
// x y
nx = x + ((ex -o.lastMouseX) * (o.hmode ? 1 : -1));
ny = y + ((ey -o.lastMouseY) * (o.vmode ? 1 : -1));
// x y
// ( )
if (o.xMapper) nx = o.xMapper(y)
else if (o.yMapper) ny = o.yMapper(x)
// x y
Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";

156
//
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
// onDrag
// x y
Drag.obj.root.onDrag(nx, ny);
return false;
},
// ,
end: function() {
// (
// )
document.onmousemove = null;
document.onmouseup = null;
//
// onDragEnd x y
Drag.obj.root.onDragEnd(
parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
// No longer watch the object for drags
Drag.obj = null;
},
// ,
fixE: function(e) {
// , IE,
// IE
if (typeof e == 'undefined') e = window.event;
// layer ,
// offset
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
return e;
}
};
, DOM-Drag, , JavaScript- .
, , -
. Scriptaculous,
, .

157
- , ,
JavaScript ,
. , DHTML, , , .

moo.fx jQuery
, :
moo.fx jQuery. ,
, .
-. 7.23
.
7.23. , moo.fx jQuery

// ,
// , , ,
//
// moo.fx
new fx.Height( "side", {
duration: 1000,
onComplete: function() {
new fx.Height( "side", { duration: 1000 } ).hide();
}
}).show();
// jQuery
$("#side").slideDown( 1000, function(){
$(this).slideUp( 1000 );
});
// , ,
// ( ),
//
// moo.fx
new fx.Combo( "body", {
height: true,
width: true,
opacity: true
}).hide();
// jQuery
$("#body").hide( "fast" );
, , , moo.fx jQuery
, . -
,
JavaScript-:

158

moo.fx: http://moofx.mad4milk.net/

mootoolkit: http://moofx.mad4milk.net/documentation/

jQuery: http://jquery.com/

jQuery: http://jquery.com/docs/fx/

Scriptaculous
- DHTML-,
Scriptaculous. Prototype, Scriptaculous
, ,
, (, ). - Scriptaculous
:

: http://script.aculo.us/

: http://wiki.script.aculo.us/scriptaculous/

: http://wiki.script.aculo.us/scriptaculous/show/Demos/
, Scriptaculous ,

, .
, .


, Scriptaculous .
( Ajax,
- ),
-. , 7.24 ,
Scriptaculous.
7.24. , ,
Scriptaculous

<html>
<head>
<title>script.aculo.us
</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="scriptaculous.js" type="text/javascript"></script>
<script src="effects.js" type="text/javascript"></script>
<script src="dragdrop.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function(){
// id 'list' ,
//
Sortable.create('list');
};
</script>
</head>
<body>
<h1> </h1>

159
<p> .</p>
<ul id="list">
<li> 1</li>
<li> 2</li>
<li> 3</li>
<li> 4</li>
<li> 5</li>
<li> 6</li>
</ul>
</body>
</html>
, , ,
,
.


Scriptaculous ,
. ,
(
) Scriptaculous ,
, 7.25.
7.25. Scriptaculous,

<html>
<head>
<title>script.aculo.us </title>
<script src="prototype.js" type="text/javascript"></script>
<script src="scriptaculous.js" type="text/javascript"></script>
<script src="effects.js" type="text/javascript"></script>
<script src="dragdrop.js" type="text/javascript"></script>
<script src="controls.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function(){
// , ID, ageHandle,
// , , ID, ageBar,
//
new Control.Slider( 'ageHandle', 'ageBar', {
//
// updateAge
onSlide: updateAge
});
//
function updateAge(v) {

160
// ,
// age
//
$('age').value = Math.floor( v * 100 );
}
};
</script>
</head>
<body>
<h1> </h1>
<form action="" method="POST">
<p> ? <input type="text" name="age" id="age" /></p>
<div id="ageBar" style="width:200px; background: #000; height:5px;">
<div id="ageHandle" style="width:5px; height:10px;
background: #000; cursor:move;"></div>
</div>
<input type="submit" value="Submit Age"/>
</form>
</body>
</html>

, -
DHTML-, ,
,
.
.

,
. , ,
.
.
,
JavaScript CSS.
.
, -
. ,
, JavaScript CSS. ,
, JavaScript- .

161

8
,
- . ,
, , , .
, ,
JavaScript, .
- , ,
.

.
, .

, .


-
, :
, . , -
.
, ,
, (, ,
, . .).
XHTML-. <input> (,
, , class text),
. 8.1.
8.1. XHTML-, JavaScript

<html>
<head>
<title> </title>
</head>
<body>
<form action="" method="POST">
<fieldset class="login">
<legend> </legend>
<label for="username" class="hover"> </label>
<input type="text" id="username" class="required text"/>
<label for="password" class="hover"></label>
<input type="password" id="password" class="required text"/>
</fieldset>
<fieldset>
<legend> </legend>
<label for="name"></label>

162
<input type="text" id="name" class="required text"/><br/>
<label for="email"> </label>
<input type="text" id="email" class="required email text"/><br/>
<label for="date"></label>
<input type="text" id="date" class="required date text"/><br/>
<label for="url">-</label>
<input type="text" id="url" class="url text" value="http://"/><br/>
<label for="phone"></label>
<input type="text" id="phone" class="phone text"/><br/>
<label for="age"> 13 ?</label>
<input type="checkbox" id="age" name="age" value="yes"/><br/>
<input type="submit" value="Submit Form" class="submit"/>
</fieldset>
</form>
</body>
</html>
CSS-,
.
. CSS 8.2.
8.2. CSS,

form {
font-family: Arial;
font-size: 14px;
width: 300px;
}
fieldset {
border: 1px solid #CCC;
margin-bottom: 10px;
}
fieldset.login input {
width: 125px;
}
legend {
font-weight: bold;
font-size: 1.1em;
}

163
label {
display: block;
width: 60px;
text-align: right;
float: left;
padding-right: 10px;
margin: 5px 0;
}
input {
margin: 5px 0;
}
input.text {
padding: 0 0 0 3px;
width: 172px;
}
input.submit {
margin: 15px 0 0 70px;
}
, . 8.1,
( JavaScript).

. 8.1. ,
JavaScript
, ,
. ,
. ,
, .

164
,
,
. ,
, ,
. JavaScript,
, JavaScript, .
,

. ,
,
.


, ,
( , ).
, .
, , , ,
,
- . , <input type=text>,
<select> <textarea>.
,
. (
), , .
8.3.
8.3. ( )

//
//
function checkRequired( elem ) {
if ( elem.type == "checkbox" || elem.type == "radio" )
return getInputsByName( elem.name ).numChecked;
else
return elem.value.length > 0 && elem.value != elem.defaultValue;
}
// (
// )
function getInputsByName( name ) {
//
var results = [];
// ,
results.numChecked = 0;
//
var input = document.getElementsByTagName("input");
for ( var i = 0; i < input.length; i++ ) {

165
//
if ( input[i].name == name ) {
// ,
//
results.push( input[i] );
// ,
//
if ( input[i].checked )
results.numChecked++;
}
}
//
return results;
}
//
window.onload = function()
// .
document.getElementsByTagName("form")[0].onsubmit = function(){
//
var elem = document.getElementById("age");
// age
if ( ! checkRequired( elem ) ) {
//
// .
alert( " " +
" 13 ". );
return false;
}
//
var elem = document.getElementById("name");
// name -
if ( ! checkRequired( elem ) ) {
// ,
// .
alert( " ,
". );
return false;
}
};
};
, ,
. ,
.

166

( )

.
,
. ,
. ,
.
,
, , URL, .


- ,
.
( ) .
, .
8.4 .
8.4.

// ,
//
function checkEmail( elem ) {
// , - ,
//
return elem.value == '' ||
/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test( elem.value );
}
//
var elem = document.getElementById("email");
//
if ( ! checkEmail( elem ) ) {
alert( " ". );
}

URL
( )
- URL. ( )
. ,
, .
-, http https ( -
, ). , URL http://,
, .
URL 8.5.

167
8.5. URL

// , URL
//
function checkURL( elem ) {
// , - ,
// http://
return elem.value == '' || !elem.value == 'http://' ||
// , URL
/^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test( elem.value );
}
//
var elem = document.getElementById("url");
// , URL
if ( ! checkURL( elem ) ) {
alert( " URL". );
}


,
: . ,
( ) ;
.
.
, (, 123-456-7890, (123) 4567890).

.
,
, , ,
.
, 8.6.
8.6.

// ,
//
function checkPhone( elem ) {
// -
//
var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec( elem.value );
// , ,

168
// : (123) 456-7890
if ( m !== null)
elem.value = "(" + m[1] + ") " + m[2] + "-" + m[3];
return elem.value == '' || m !== null;
}
//
var elem = document.getElementById("phone");
//
if ( ! checkPhone( elem ) ) {
alert( " ". );
}

.
, (//). , ,
, , ,
.
, 8.7.
8.7.

// ,
//
function checkDate( elem ) {
// , - ,
// //
return !elem.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(elem.value);
}
//
var elem = document.getElementById("date");
//
if ( ! checkDate( elem ) ) {
alert( " ". );
}

. ,
, .
8.8.
8.8.

169
var errMsg = {
//
required: {
msg: " ".,
test: function(obj,load) {
//
//
// ( ' '
// )
return obj.value.length > 0 || load || obj.value ==
obj.defaultValue;
}
},
//
email: {
msg: " ".,
test: function(obj) {
// , - ,
//
return !obj.value ||
/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(
obj.value );
}
},
// , ,
//
phone: {
msg: " ".,
test: function(obj) {
// ,

//
var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec( obj.value );
// , , ,
// : (123) 456-7890
if ( m ) obj.value = "(" + m[1]+") " + m[2]+"-"+m[3];
return !obj.value || m;
}
},
// ,
// //
date: {
msg: " ".,
test: function(obj) {

170
// , - ,
// //
return !obj.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(obj.value);
}
},
// , URL
url: {
msg: "URL ".,
test: function(obj) {
// , - ,
//
// http://
return !obj.value || obj.value == 'http://' ||
// ,
// URL
/^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test(
obj.value );
}
}
};
, , ,
, .


, , ,
.
.
, ,
, .


, ,
,
- .

HTML DOM-. <form>- ( DOM)


elements. ,
,
.

. , required ()
- . ,
, 8.8.

171
, ,
(
). 8.9.
8.9. , , ,

// .
// form
// load ,
// ,
function validateForm( form, load ) {
var valid = true;
//
// form.elements
for ( var i = 0; i < form.elements.length; i++ ) {
// ,
hideErrors( form.elements[i] );
//
if ( ! validateField( form.elements[i], load ) )
valid = false;
}
// false, ,
// true,
return valid;
}
//
function validateField( elem, load ) {
var errors = [];
//
//
for ( var name in errMsg ) {
// , ,
var re = new RegExp("(^|\\s)" + name + "(\\s|$)");
// , ,
//
if ( re.test( elem.className ) && !errMsg[name].test( elem, load ) )
// ,
//
errors.push( errMsg[name].msg );
}

172
// ,
if ( errors.length )
showErrors( elem, errors );
// false, -
//
return errors.length > 0;
}
, ,
, . ,
.
,
. , ,
8.10.
8.10. ,

// ,
//
function hideErrors( elem ) {
//
var next = elem.nextSibling;
// ul errors
if ( next && next.nodeName == "UL" && next.className == "errors" )
// ( '')
elem.parenttNode.removeChild( next );
}
//
//
function showErrors( elem, errors ) {
//
var next = elem.nextSibling;
//
//
if ( next && ( next.nodeName != "UL" || next.className
!= "errors" ) ) {
//
next = document.createElement( "ul" );
next.className = "errors";
// DOM-
elem.paretNode.insertBefore( next, elem.nextSibling );
}

173
// , UL
//
for ( var i = 0; i < errors.length; i++ ) {
// li
var li = document.createElement( "li" );
li.innerHTML = errors[i];
// DOM
next.appendChild( li );
}
}
, JavaScript ,
- , . CSS,
, 8.11.
8.11. CSS,

ul.errors {
list-style: none;
background: #FFCECE;
padding: 3px;
margin: 3px 0 3px 70px;
font-size: 0.9em;
width: 165px;
}
, ,
JavaScript , . 8.2 ( ,
, ).
, , ( ,
) , ,
.
, .
, .

174

. 8.2.



. ( )
: , ,
. , .
.

,
,
, . ,
, ,
Submit (
Enter). , -
, ,
. - - ,
, (
submit).
8.12.
8.12.

function watchForm( form ) {

175
//
addEvent( form, 'submit', function(){
//
return validateForm( form );
});
}
//
var form = document.getElementsByTagName( "form" )[0];
// ,
watchForm( form );


, ,
. keypress,
.
. ( )
, , , .
, . ,
, .
,
( , ).
,
, ,
.
8.13.
8.13.

function watchFields( form ) {


//
for ( var i = 0; i < form.elements.length; i++ ) {
// 'change' (
// )
addEvent( form.elements[i], 'change', function(){
// ,
return validateField( this );
});
}
}
//
var form = document.getElementsByTagName( "form" )[0];

176
//
watchFields( form );


, ,
, .
, (
), ,
, .
.
,
, .
, ,
8.14.
8.14.

addEvent( window, "load", function() {


//
var forms = document.getElementsByTagName("form");
//
for ( var i = 0; i < forms.length; i++ ) {
// , 'load'
// true, ,
//
validateForm( forms[i], true );
}
});
, ,
, , :
. , ,
, .


, -,
.
, ,
.
JavaScript
DOM- , .

JavaScript-

jQuery

(http://jquery.com/), , , DOM- .

177
, ()
, , .
. ,
( , ).
, .
username
password, , . 8.3.

. 8.3.
JavaScript, ,
. .
, .
-, ,
, div-. div ,
.
-, , ,
( ). , ,
, - , , .
, , ,
( ).
, ,
, 8.15.
8.15. , , JavaScript jQuery

// , ,
// hover
$("label.hover+input")

178
// div ( hover-wrap),
// HTML:
// <div class='hover-wrap'><input type="text" ;/></div>
.wrap("<div class='hover-wrap'></div>")
//
// ( , )
.focus(function(){
$(this).prev().hide();
})
//
// ( - ).
.blur(function(){
if ( !this.value ) $(this).prev().show()
})
//
.each(function(){
// <div class='hover-wrap'></div>
$(this).before( $(this).parent().prev() );
// ,
//
if ( this.value ) $(this).prev().hide();
});
JavaScript . - ,
, CSS.
8.16.
8.16. CSS, ,

div.hover-wrap {
position: relative;
display: inline;
}
div.hover-wrap input.invalid {
border: 2px solid red;
}
div.hover-wrap ul.errors {
display: none;
}
div.hover-wrap label.hover {
position: absolute;

179
top: -0.7em;
left: 5px;
color: #666;
}
, , ,
. :
, .


, , . - -
. , ,
, .
JavaScript. . 8.4.

. 8.4. -

, .
title , (
, ). , ,
8.17.
8.17.

(*)

JavaScript- jQuery

// , (required)
$("input.required")
//
.prev("label")
//
//

180
.css("cursor", "help")
//
//
.title( errMsg.required )
// , (*) ,
//
.append(" <span class='required'>*</span>");

(.

8.18).
8.18. CSS (*)

label span.required {
color: red;
}
,
JavaScript . ,

JavaScript.

, -, ,
, JavaScript
. , , . 8.5.

181

. 8.5. , JavaScript
,
, .
,
, .
,
.
, ,
, .

182

9
DOM, CSS
, -
. ( )
, .
.
.
, ,
, , ,
JavaScript. ,
. ,
-.
, ,
DOM, JavaScript CSS.


, ,
, . ,
, ,
.
:

,
, .

,
( , ).

- .

- .
,

Lightbox ThickBox.

Lightbox
Lightbox DOM- .
, .
( -
JavaScript-). (
).
http://www.huddletogether.com/projects/lightbox/ http://particletree.com/ features/lightboxgone-wild/, Lightbox, JavaScript- Prototype.
. 9.1 Lightbox ,
.

183

. 9.1. Lightbox ,
Lightbox .
HTML- HTML ,
, :

<a href="images/image-1.jpg" rel="lightbox" title="


"> 1</a>
, , ( ,
DOM, ). ,
DOM- (. 9.1) .
9-1. (anchor)

// anchor
var anchors = document.getElementsByTagName("a");
// anchor
for ( var i=0; i < anchors.length; i++ ) {
var anchor = anchors[i];
// "lightbox"
if ( anchor.href && anchor.rel == "lightbox" ) {

184
// Lightbox
anchor.onclick = function () {
showLightbox(this);
return false;
};
}
}
Lightbox ,
, , .
, Lightbox .

ThickBox
, ThickBox,
(Cody Lindley), JavaScript- jQuery.
Lightbox, Ajax HTML.

(http://codylindley.com/Javascript/257/thickbox-one-box-to-rule-them-all),

(http:// jquery.com/demo/thickbox/).
(. . 9.2), ThickBox
Lightbox. Lightbox, ThickBox
. , DOM , thickbox, :

<a href="ajaxLogin.htm?height=100&width=250" class="thickbox">ThickBox login</a>

185

. 9.2. ThickBox
9.2 , ThickBox
, DOM ( ,

).
9.2. anchor,
thickbox

// thickbox, DOM
$(document).ready(function(){
// thickbox href, .thickbox
$("a.thickbox").click(function(){
// thickbox
var t = this.title || this.name || this.href || null;
// thickbox
TB_show(t,this.href);
//
this.blur();
//

186
return false;
});
});
, ThickBox,
, Lightbox.
, ,
, , .


,
. ,
, . ,
JavaScript,
. , JavaScript (
CSS) .
HTML-, , 9.3.
9.3. HTML- ,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> </title>
</head>
<body>
<h1> </h1>
<p>Lorem ipsum dolor . . . </p>
<!- , <ul>, class
"gallery", title .
--->
<ul class="gallery" title=" ">
<!-
<li>, , .
, class
"tall".
-->
<li><a href="image1.jpg"><img src="image1.jpg"
alt=" "/></a></li>
<li><a href="image2.jpg"><img src="image2.jpg"
alt=" "/></a></li>

187
<li class="tall"><a href="image3.jpg"><img src="image3.jpg"
alt=" "/></a></li>
<li class="tall"><a href="image4.jpg"><img src="image4.jpg"
alt=" "/></a></li>
<li><a href="image5.jpg"><img src="image5.jpg"
alt=" "/></a></li>
</ul>
<p>Lorem ipsum dolor . . . </p>
</body>
</html>
,
. CSS 9.4 9-4.
9.4. CSS

body {
font-family: Arial;
font-siz: 14px;
}
/* . */
ul.gallery {
list-style: none;
padding: 5px;
background: #EEE;
overflow: auto;
border: 1px solid #AAA;
margin-top: 0px;
}
/* . */
ul.gallery li {
float: left;
margin: 6px;
width: 110px;
height: 110px;
background: #FFF;
border: 2px solid #AAA;
}
/* 100px */
ul.gallery img {
width: 100px;
margin: 5px;
border: 0px;
margin-top: 17px;

188
}
/* 100px */
ul.gallery li.tall img {
height: 100px;
width: auto;
margin-top: 5px;
margin-left: 17px;
}
HTML CSS . 9.3. ,
HTML, ,
, JavaScript .

. 9.3. -,


, ,
. ( ) HTML -, ,

189
. HTML- DOM
-, . 9.5.
9.5. HTML DOM

// ,
var curImage = null;
// ,
// DOM
window.onload = function() {
/*
* DOM-:
* <div id="overlay"></div>
* <div id="gallery">
* <div id="gallery_image"></div>
* <div id="gallery_prev"><a href="">&laquo; </a></div>
* <div id="gallery_next"><a href=""> &raquo;</a></div>
* <div id="gallery_title"></div>
* </div>
*/
//
var gallery = document.createElement("div");
gallery.id = "gallery";
// div
gallery.innerHTML = '<div id="gallery_image"></div>' +
'<div id="gallery_prev"><a href="">&laquo; </a></div>' +
'<div id="gallery_next"><a href=""> &raquo;</a></div>' +
'<div id="gallery_title"></div>';
// gallery DOM
document.body.appendChild( gallery );
//
//
id("gallery_next").onclick = nextImage;
id("gallery_prev").onclick = prevImage;
//
var g = byClass( "gallery", "ul" );
//
for ( var i = 0; i < g.length; i++ ) {
//
var link = tag( "a", g[i] );

190
//
for ( var j = 0; j < link.length; j++ ) {
// ,
//
//
link[j].onclick = function(){
//
showOverlay();
//
showImage( this.parentNode );
//
//
return false;
};
}
//
//
addSlideShow( g[i] );
}
};
,
.


, Lightbox,
ThickBox. , ,
: .
, 7 :
pageWidth() pageHeight().
div-, ID (
) DOM. 9.6.
9.6. div- DOM

//
var overlay = document.createElement("div");
overlay.id = "overlay";
//
overlay.onclick = hideOverlay;
// DOM
document.body.appendChild( overlay );

191
, .
. ,
.
100%, ,
( ). ,
. ,
pageHeight() pageWidth(), 7.
9.7.
9.7. , ,

//
function hideOverlay() {
//
curImage = null;
//
hide( id("overlay") );
hide( id("gallery") );
}
//
function showOverlay() {
//
var over = id("overlay");
//
// ( )
over.style.height = pageHeight() + "px";
over.style.width = pageWidth() + "px";
//
fadeIn( over, 50, 10 );
}
, CSS, .
9.8.
9.8. CSS,

#overlay {
background: #000;
opacity: 0.5;
display: none;
position: absolute;
top: 0px;
left: 0px;
width: 100%;

192
height: 100%;
z-index: 100;
cursor: pointer;
cursor: hand;
}
, HTML CSS ,
. 9.4.

. 9.4. ,
, ,
.


, ,
. , - CSS 2
, .
CSS, (
, ).
, DOM- ,
9.9 ( , 9.5).
9.9. HTML

193
<div id="gallery">
<div id="gallery_image"></div>
<div id="gallery_prev"><a href="">&laquo; </a></div>
<div id="gallery_next"><a href=""> &raquo;</a></div>
<div id="gallery_title"></div>
</div>
HTML-, div . ,

( HTML-),
. , , 9.10.
9.10.

//
function showImage(cur) {
//
curImage = cur;
//
var img = id("gallery_image");
// ,
if ( img.firstChild )
img.removeChild( img.firstChild );
//
img.appendChild( cur.firstChild.cloneNode( true ) );
//
// 'alt'
id("gallery_title").innerHTML = cur.firstChild.firstChild.alt;
//
var gallery = id("gallery");
// ( )
gallery.className = cur.className;
//
fadeIn( gallery, 100, 10 );
//
//
adjust();
}
showImage adjust.
(

194
). ,
, 9.11.
9.11. , ,

//
//
function adjust(){
// Locate the gallery
var obj = id("gallery");
//
if ( !obj ) return;
//
var w = getWidth( obj );
var h = getHeight( obj );
//
var t = scrollY() + ( windowHeight() / 2 ) - ( h / 2 );
//
if ( t < 0 ) t = 0;
//
var l = scrollX() + ( windowWidth() / 2 ) - ( w / 2 );
// ,
if ( l < 0 ) l = 0;
//
setY( obj, t );
setX( obj, l );
};
//
//
window.onresize = document.onscroll = adjust;

9.12

CSS,

div- z-index,
, .
9.12. CSS

195
#gallery {
position: absolute;
width: 650px;
height: 510px;
background: #FFF;
z-index: 110;
display: none;
}
#gallery_title {
position: absolute;
bottom: 5px;
left: 5px;
width: 100%;
font-size: 16px;
text-align: center;
}
#gallery img {
position: absolute;
top: 5px;
left: 5px;
width: 640px;
height: 480px;
border: 0px;
z-index: 115;
}
#gallery.tall {
width: 430px;
height: 590px;
}
#gallery.tall img {
width: 420px;
height: 560px;
}
, CSS, HTML JavaScript,
, , . 9.5, .

196

. 9.5. ,
,
.

(
),
. , HTML ,
, .
-, .
, ,
(
curImage). , , ,
(. 9.13).
9.13. , ,

//
function prevImage() {

197
//
//
showImage( prev( curImage ) );
//
return false;
}
//
function nextImage() {
//
//
showImage( next( curImage ) );
//
return false;
}
, ,
. , ,
, .
showImage() ,
. , 9.14.
9.14. ,

// ,
if ( !next(cur) )
hide( id("gallery_next") );
// ,
else
show( id("gallery_next") );
// ,
if ( !prev(cur) )
hide( id("gallery_prev") );
// ,
else
show( id("gallery_prev") );

, 9.15 CSS,
.
9.15. CSS,

#gallery_prev, #gallery_next {

198
position: absolute;
bottom: 0px;
right: 0px;
z-index: 120;
width: 60px;
text-align: center;
font-size: 12px;
padding: 4px;
}
#gallery_prev {
left: 0px;
}
#gallery_prev a, #gallery_next a {
color: #000;
text-decoration: none;
}
. 9.5 . ,
,
. ,
.


,
: , .
,
. . :

,
.

( , ,
).
9.16.
9.16. DOM

function addSlideshow( elem ) {


//
// ,
//
var div = document.createElement("div");
div.className = "slideshow";

199
//
var span = document.createElement("span");
span.innerHTML = g[i].title;
div.appendChild( span );
// ,
//
var a = document.createElement("a");
a.href = "";
a.innerHTML = "&raquo; ";
//
a.onclick = function(){
startShow( this.parentNode.nextSibling );
return false;
};
//
div.appendChild( a );
elem.parentNode.insertBefore( div, elem );
}
.
,
( , ).
, , . , ,
. 9.17.
9.17. ,

// ,
function startShow(obj) {
//
var elem = tag( "li", obj );
//
var gallery = id("gallery");
// ,
for ( var i = 0; i < elem.length; i++ ) new function() {
// ,
var cur = elem[i];
// 5
setTimeout(function(){
//
showImage( cur );
// 3,5

200
// ( 1 )
setTimeout(function(){
fadeOut( gallery, 0, 10 );
}, 3500 );
}, i * 5000 );
};
// ,
setTimeout( hideOverlay, 5000 * elem.length );
//
showOverlay();
}
CSS .
9.18.
9.18. CSS

div.slideshow {
text-align: right;
padding: 4px;
margin-top: 10px;
position: relative;
}
div.slideshow span {
position: absolute;
bottom: 3px;
left: 0px;
font-size: 18px;
font-weight: bold;
}
div.slideshow a {
color: #000;
}
, , . 9.6
, .

). ,
, , ,
, .

201

. 9.6. ,

, ,

DOM-

-, -
. , , ,
DOM- .
,
. HTML-
, ( ,
). ,
.
, .

1 0 Ajax

202
Ajax , (Jesse James Garrett) Adaptive
Path ,
XMLHttpRequest, . Ajax ,
Asynchronous JavaScript XML, ,
-. , Ajax
, , XML HTML.
Ajax- (
). ,
, JavaScript- ,
. :

HTTP- ,
.

http- , ,
.

, , .
, Ajax- ,

, , , .
11, 12 13, Ajax-.

Ajax
Ajax- ,
. , ,
, ,
. ,
( ) .
, , , .
Ajax , , , , Instant Domain Search (http:// instantdomainsearch.com/), . 10.1.

. 10.1. Instant Domain Search

HTTP-

203
, , Ajax ,
HTTP-. Hypertext Transfer Protocol (HTTP) HTML

HTTP- JavaScript. ,
-.

Ajax.
, .
, ,
HTTP-. ,
, .


Ajax- .
, ,
, .
XMLHttpRequest.

XMLHttpRequest:

Internet Explorer, ,
ActiveXObject (
Internet Explorer). , Internet Explorer 7
XMLHttpRequest.

XMLHttpRequest
. Firefox, Opera Safari.
,

Internet

Explorer

XMLHttpRequest , ,
. XMLHttpRequest ,
. 10.1 , GET.
10.1. HTTP GET-

// IE, XMLHttpRequest
//
if ( typeof XMLHttpRequest == "undefined" )
XMLHttpRequest = function(){
// Internet Explorer XMLHttpRequest
// ActiveXObject
return new ActiveXObject(
// IE 5 XMLHTTP , ,
// IE 6
navigator.userAgent.indexOf("MSIE 5") >= 0 ?
"Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"

204
);
};
//
var xml = new XMLHttpRequest();
//
xml.open("GET", "/some/url.cgi", true);
//
//
xml.send();
, , , ,

(, );
HTTP .
Ajax (, ) . ,
.

(). ,
:

JavaScript, -
( , ).

( ,
, ,
, ).
10.2 ,

, , .
10.2. JavaScript-,

// , -
{
name: "John",
last: "Resig",
city: "Cambridge",
zip: 02140
}
//
name=John&last=Resig&city=Cambridge&zip=02140

205
// ,
[
{ name: "name", value: "John" },
{ name: "last", value: "Resig" },
{ name: "lang", value: "JavaScript" },
{ name: "lang", value: "Perl" },
{ name: "lang", value: "Java" }
]
//
name=John&last=Resig&lang=JavaScript&lang=Perl&lang=Java
// (
// id(), , DOM)
[
id( "name" ),
id( "last" ),
id( "username" ),
id( "password" )
]
//
name=John&last=Resig&username=jeresig&password=test
, HTTP. , , HTTP GET-, :

http://someurl.com/?name=John&last=Resig
POST- ( ,
). .

10.2. , , 10.3.
,
, .
10.3. HTTP

// .
// :
// -
// - , -
//
function serialize(a) {
//
var s = [];
// , ,
//

206
if ( a.constructor == Array ) {
//
for ( var i = 0; i < a.length; i++ )
s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
// , , ,
// -
} else {
// -
for ( var j in a )
s.push( j + "=" + encodeURIComponent( a[j] ) );
}
//
return s.join("&");
}
( ), ,
, GET- POST-.

GET-
HTTP GET- XMLHttpRequest,
, .
10.4.
10.4. HTTP GET- (
)

//
var xml = new XMLHttpRequest();
// GET-
xml.open("GET", "/some/url.cgi?" + serialize( data ), true);
//
xml.send();
, URL (
?). - - , ,
-.
( )
.

POST-
HTTP- , XMLHttpRequest, POST,
. POST-
( ).

207
,
application/x-www-form-urlencoded. ,
XML ( text/xml application/ xml) JavaScript (
application/json).
10.5
.
10.5. HTTP POST- (
)

//
var xml = new XMLHttpRequest();
// POST-
xml.open("POST", "/some/url.cgi", true);
// (content-type),
// ,
xml.setRequestHeader(
"Content-Type", "application/x-www-form-urlencoded");
//
// , Mozilla
//
if ( xml.overrideMimeType )
xml.setRequestHeader("Connection", "close");
//
//
xml.send( serialize( data ) );
,
, . 10.6.
10.6. POST-, XML

//
var xml = new XMLHttpRequest();
// POST-
xml.open("POST", "/some/url.cgi", true);
// , ,
// XML-
xml.setRequestHeader( "Content-Type", "text/xml");
// ,
// Mozilla
if ( xml.overrideMimeType )

208
xml.setRequestHeader("Connection", "close");
//
xml.send( "<items><item id='one'/><item id='two'/></items>" );
( GET, , , ,
).
, , XML-RPC SOAP.
, ,
, HTTP .

HTTP

XMLHttpRequest,

, ,
. Ajax: XML (
, Ajax- XML. ,
).
10.7 ,
.
10.7.

//
var xml = new XMLHttpRequest();
// POST-
xml.open("GET", "/some/url.cgi", true);
//
xml.onreadystatechange = function(){
// ,
if ( xml.readyState == 4 ) {
// xml.responseXML XML- (
// )
// xml.responseText
// ( XML-)
//
xml = null;
}
};
//
xml.send();

209
, ,
HTTP. , responseXML responseText, ,
. , XML-, DOM-
responseXML; responseText.
, , ,
onreadystatechange ( 10.7),
.


, XMLHttpRequest -
, .

, :

:
HTTP, HTTP-
, . ,
200.

, : Not
Modified ( 304). , , ,
, , - . , .

: Ajax- (
-), , . ,
,
.

, Safari:
( IF-MODIFIED-SINCE).
.
, 10.8, ,

.
10.8.

HTTP

// , XMLHttpRequest .
// XMLHttpRequest
function httpSuccess(r) {
try {
// ,
// , ,
return !r.status && location.protocol == "file:" ||
// 200
( r.status >= 200 && r.status < 300 ) ||
// ,
r.status == 304 ||

210
// , Safari
//
navigator.userAgent.indexOf("Safari") >= 0 &&
typeof r.status == "undefined";
} catch(e){}
// , ,
//
return false;
}
HTTP ; , -
(, XML-
HTML).
Ajax- Ajax-.


, XMLHttpRequest,
, .
Implementing this feature isnt as cut-and-dry, but determining the success state of
the request (as you did in the previous section) is possible with a little bit of work.
Listing 10-9 shows how you would go about checking for a request time-out in an application of your own.
10.9.

//
var xml = new XMLHttpRequest();
// POST-
xml.open("GET", "/some/url.cgi", true);
// 5
var timeoutLength = 5000;
//
var requestDone = false;
// ,
// 5 , ( )
setTimeout(function(){
requestDone = true;
}, timeoutLength);
//
xml.onreadystatechange = function(){
// , ,

211
// ,
if ( xml.readyState == 4 && !requestDone ) {
// xml.responseXML XML- ( )
// xml.responseText
// ( XML- )
//
xml = null;
}
};
//
xml.send();
, ,
, .


,
, ,
. XMLHttpRequest ,
. ( XML), (
JSON). ,
, :

XML: , XML-,
DOM-.

HTML: XML- ,
, HTML-.

JavaScript/JSON: , JavaScript,
JavaScript JSON (JavaScript Object Notation).
,

. , , XML-
HTML. HTTP
XMLHttpRequest:

responseXML: DOM-
( XML) XML-.
Content-type: text/xml,
XML.

responseText:
. : HTML JavaScript.
,

HTTP ( , XML-
). 10.10 ,
.

212
10.10. , HTTP-

// HTTP
// , XMLHttpRequest
// ,
// : xml, script, text html
// "",
// content-type
function httpData(r, type) {
// content-type
var ct = r.getResponseHeader("content-type");
// ,
// - XML
var data = !type && ct && ct.indexOf("xml") >= 0;
// XML-, XML,
//
data = type == "xml" || data ? r.responseXML : r.responseText;
// "script", ,
// , JavaScript
if ( type == "script" )
eval.call( window, data );
// , ( XML-,
// )
return data;
}
, , ,
, Ajax- .
.

Ajax-
,
Ajax- .
Ajax-,
.
Ajax- 10.11.
10.11.

Ajax

// , Ajax-
// , ,
// ,
//
function ajax( options ) {

213
// ,
//
options = {
// http-
type: options.type || "POST",
// URL
url: options.url || "",
//
timeout: options.timeout || 5000,
// , , ,
// ( )
onComplete: options.onComplete || function(){},
onError: options.onError || function(){},
onSuccess: options.onSuccess || function(){},
//
// ,
// , .
data: options.data || ""
};
//
var xml = new XMLHttpRequest();
//
xml.open(options.type, options.url, true);
// 5
// ,
var timeoutLength = options.timeout;
//
var requestDone = false;
// ,
// 5 , ( )
setTimeout(function(){
requestDone = true;
}, timeoutLength);
//
xml.onreadystatechange = function(){
// , ,
// ,

214
if ( xml.readyState == 4 && !requestDone ) {
//
if ( httpSuccess( xml ) ) {
//
// ,
options.onSuccess( httpData( xml, options.type ) );
// ,
//
} else {
options.onError();
}
// ,
//
options.onComplete();
//
xml = null;
}
};
//
xml.send();
// HTTP
function httpSuccess(r) {
try {
// ,
// ,
//

return !r.status && location.protocol == "file:" ||


// 200
( r.status >= 200 && r.status < 300 ) ||
// ,
//
r.status == 304 ||
// , Safari
//
navigator.userAgent.indexOf("Safari") >= 0
&& typeof r.status == "undefined";
} catch(e){}

215
// , ,
//
return false;
}
// HTTP
function httpData(r,type) {
// content-type
var ct = r.getResponseHeader("content-type");
// ,
// - XML
var data = !type && ct && ct.indexOf("xml") >= 0;
// XML-, XML,
//
//
data = type == "xml" || data ? r.responseXML : r.responseText;
// "script", ,
// , JavaScript
if ( type == "script" )
eval.call( window, data );
// , ( XML-,
// )
return data;
}
}
, , , ,
, . ,
( ). ,
, ,
Ajax.


Ajax- , ,
, , . ,
, .
,
.

RSS-, XML
XML,
.
XML-, DOM-.
, , ,

216
DOM-. ,
XML- getElementById . ,
-HTML XML-
ID. , XML- .
XML -
RSS-.
10.12. , RSS-,
XML

<html>
<head>
<title> RSS-</title>
<! Ajax- -->
<script src="ajax.js"></script>
<script>
//
window.onload = function(){
// RSS- Ajax
ajax({
// URL RSS-
url: "rss.xml",
// XML-
type: "xml",
// ,
onSuccess: function( rss ) {
// id "feed",
// <ol>
var feed = document.getElementById("feed");
// RSS XML-
var titles = rss.getElementsByTagName("title");
//
//
for ( var i = 0; i < titles.length; i++ ) {
// <li>-
//
var li = document.createElement("li");
//
li.innerHTML = titles[i].firstChild.nodeValue;
// DOM, <ol>-
feed.appendChild( li );

217
}
}
});
};
</script>
</head>
<body>
<h1> RSS-</h1>
<p> RSS-:</p>
<!-- RSS- -->
<ol id="feed"></ol>
</body>
</html>
, , , Ajax- -
, . ,
XML-,
.

HTML
, Ajax
HTML-. XML , ,
; .

-. 10.13.
10.13. HTML- -

<html>
<head>
<title> HTML, Ajax </title>
<!-- Ajax- -->
<script src="ajax.js"></script>
<script>
//
window.onload = function(){
// Ajax
ajax({
// URL, HTML
url: "scores.html",
// HTML-
type: "html",
// ,
onSuccess: function( html ) {
// HTML div-,
// id 'scores'

218
var scores = document.getElementById("scores");
// HTML
scores.innerHTML = html;
}
});
};
</script>
</head>
<body>
<h1> HTML, Ajax </h1>
<!-- -->
<div id="scores"></div>
</body>
</html>
HTML- , -
,
.
HTML- ,
- .

JSON JavaScript:
( ,
13, wiki), JSON JavaScript.
JSON- XML-
. , JavaScript
. ,
JavaScript, 10.14.
10.14. JavaScript-

<html>
<head>
<!-- Ajax- -->
<script src="ajax.js"></script>
<script>
// JavaScript-
ajax({
// URL JavaScript-
url: "myscript.js",
// JavaScript
type: "script"
});
</script>
</head>
<body></body>

219
</html>

Ajax

. ,

JavaScript,

.
Ajax, http- ,
, .
,
-.
, Ajax.

220

1 1 Ajax
, Ajax,
-. ,
-,
.
, , .
, , , ,
.
.

JavaScript, Ajax.
,
-.


,
- . ,
-, ,
. ()
, .
, Ajax.
, , :

- , .

,
.

, .
WordPress, (http://wordpress.org/),
.

,
, -.
WordPress,
. ,
WordPress, .


,
WordPress. Kubrik, . . 11.1
, Kubrik.

221

. 11.1. Kubrik, WordPress


, , .
; .
11.1 HTML, .
11.1. HTML, Kubrik WordPress

<html>
<head>
<title> Wordpress</title>
<script>
<!-- -->
</script>
</head>
<body>
<div id="page">
<div id="header">
<! -->
</div>
<div id="content">
<!-- -->
<div class="post">
<!-- -->

222
<h2><a href=" /test/?p=1"> </a></h2>
<small>24 2006 </small>
<div class="entry">
<!-- -->
</div>
<p class="postmetadata">
<a href="/test/?p=1#comments"></a></p>
</div>
<!-- ... -->
</div>
</div>
</body>
</html>
, <div>- ID,
content.

. DOM-,
. 11.2 DOM, .
11.2. DOM HTML,

// <div>- ID,
// "content"
var content = document.getElementById("content");
//
// RSS-
var items = rss.getElementsByTagName("item");
for ( var i = 0; i < items.length; i++ ) {
// ,
// ,
var data = getData( items[i] );
// <div>-
var div = document.createElement("div");
div.className = "post";
//
var h2 = document.createElement("h2");
// ,
// .
h2.innerHTML = "<a href='" + data.link + "'>" + data.title + "</a>";

223
// <div>-
div.appendChild( h2 );
// <div>,
var entry = document.createElement("div");
entry.className = "entry";
// <div>
entry.innerHTML = data.desc;
div.appendChild( entry );
// ,
var meta = document.createElement("p");
meta.className = "postmetadata";
var a = document.createElement("a");
a.href = data.link + "#comments";
a.innerHTML = "";
meta.appendChild( a );
div.appendChild( meta );
//
content.appendChild( div );
}
DOM- , , .
, ,
, DOM-.


WordPress . WordPress
RSS-, .
, ,
-. , , .
URL RSS- WordPress : /blog/ ?feed=rss;
, /blog/?feed=rss&paged=N,
( N 1 , 2 , . .).
11.2 , RSS-, .
11.3. XML RSS-, WordPress,

<?xml version="1.0" encoding="UTF-8"?>


<rss version="2.0">

224
<channel>
<title>Test Wordpress Web log</title>
<link>http://someurl.com/test/</link>
<description>Test Web log.</description>
<pubDate>Fri, 08 Oct 2006 02:50:23 +0000</pubDate>
<generator>http://wordpress.org/?v=2.0</generator>
<language>en</language>
<item>
<title>Test Post</title>
<link>http://someurl.com/?p=9</link>
<pubDate>Thu, 07 Sep 2006 09:58:07 +0000</pubDate>
<dc:creator>John Resig</dc:creator>
<category>Uncategorized</category>
<description><![CDATA[ ...]]>
</description>
</item>
<!-- -->
</channel>
</rss>
RSS- XML-,
( JavaScript). 11.4 ,
RSS XML- .
11.4. XML RSS-

// ,
// RSS-
var items = rss.getElementsByTagName("item");
for ( var i = 0; i < items.length; i++ ) {
// <item>- RSS- ,
//
var title = elem.getElementsByTagName("title")[0].firstChild.nodeValue;
var desc =
elem.getElementsByTagName("description")[0].firstChild.nodeValue;
var link = elem.getElementsByTagName("link")[0].firstChild.nodeValue;
}
, HTML, Ajax-
.

225
, ,
.
, .
;
.
( ). ,
, 7 ,
: pageHeight (
), scrollY ( , ),
windowHeight ( ). 11.5.
11.5.

// ,
// ,
//
window.onscroll = function(){
//
if ( curPage >= 1 && !loading &&
pageHeight() -scrollY() -windowHeight() < windowHeight() ) {
// RSS XML- Ajax
}
};
, Ajax-,
, , .

Ajax-
, . :
URL ( ) HTTP GET-
XML-. , 11.6,
Ajax- ( 10).
11.6. Ajax-

// ajax()
ajax({
// -, GET
type: "GET",
// RSS-, XML-
data: "xml",
// RSS- N- .
// '1',
// 2
url: "./?feed=rss&paged=" + ( ++curPage ),

226
// RSS-
onSuccess: function( rss ){
// RSS XML-, DOM
}
});
,
, WordPress-.

DOM RSS XML, ,


, Ajax-,
,

. 11.7 ,
WordPress .
11.7.

JavaScript,

WordPress

// ""
var curPage = 1;
//
var loading = false;
//
// ,
//
window.onscroll = function(){
//
// 1) .
// 2) -
//

// 3) ,
//

if ( curPage >= 1 && !loading


&& pageHeight() -scrollY() -windowHeight() < windowHeight() ) {
// , .
loading = true;
// ,
// ajax()
ajax({
// -, GET
type: "GET",

227
// RSS-, XML-
data: "xml",
// RSS- N- .
// '1',
//
// 2
url: "./?feed=rss&paged=" + ( ++curPage ),
// RSS-
onSuccess: function( rss ){
// <div>,
// ID "content"
var content = document.getElementById("content");
//
// , RSS-
var items = rss.getElementsByTagName("item");
for ( var i = 0; i < items.length; i++ ) {
//
content.appendChild( makePost( items[i] ) );
}
// XML- ,
// ,
if ( items.length == 0 ) {
curPage = 0;
}
},
// ,
//
onComplete: function(){
loading = false;
}
});
}
};
// , DOM-
//
function makePost( elem ) {
// ,
//
var data = getData( elem );

228
// <div>-
var div = document.createElement("div");
div.className = "post";
//
var h2 = document.createElement("h2");
// ,
// .
h2.innerHTML = "<a href='" + data.link + "'>" + data.title + "</a>";
// <div>-
div.appendChild( h2 );
// <div>,
var entry = document.createElement("div");
entry.className = "entry";
// <div>
entry.innerHTML = data.desc;
div.appendChild( entry );
// ,
var meta = document.createElement("p");
meta.className = "postmetadata";
meta.innerHTML = "<a href='" + data.link + "#comments'></a>";
div.appendChild( meta );
return div;
}
// DOM-
function getData( elem ) {
//
return {
// <item> RSS- ,
//
title: elem.getElementsByTagName("title")[0].firstChild.nodeValue,
desc:
elem.getElementsByTagName("description")[0].firstChild.nodeValue,
link: elem.getElementsByTagName("link")[0].firstChild.nodeValue
};
}
WordPress,
, , . 11.2. ,
(
).

229

. 11.2. ,

Ajax.
, .
,
. -
, .
,
Ajax-,
.


, ,
, , ,
WordPress.

,
, .

, .
, , ,
.

230
Ajax .

RSS-

. ,
:

( ,
).

.
, 11.8, ,

.
11.8. , RSS-, XML

//
//
setInterval(function(){
// ajax()
ajax({
// -, GET
type: "GET",
// RSS-, XML-
data: "xml",
// RSS- (
// )
url: "./?feed=rss&paged=1",
// RSS-
onSuccess: function( rss ){
// <div>,
// ID "content"
var content = document.getElementById("content");
// URL ( ,
// )
var recentURL =
content.getElementsByTagName("h2")[0].firstChild.href;
//
// , RSS-
var items = rss.getElementsByTagName("item");
//

231
//
var newItems = [];
//
for ( var i = 0; i < items.length; i++ ) {
//
// ""
if ( getData( items[i] ).link == recentURL )
break;
//
newItems.push( items[i] );
}
//
// ,
// -
for ( var i = newItems.length -1; i >= 0; i--) {
//
content.insertBefore( makePost( newItems[i] ),
content.firstChild );
}
}
});
//
}, 60000 );
WordPress ( ,
) , ,
. 11.3.

232

. 11.3. WordPress ,

, ,
. .
-, ,
.

, , ,
Ajax
.

XML-

HTML

, -.
- WordPress.

. ,
. ,
, , ,
. ,
, .

Ajax: .

233

1 2
, Ajax-
,
.
. ,
, . ,
, ( ),
.
,
. , , ,
, Ajax-,
.


. , Google

Google

Suggest

(http://www.google.com/webhp?complete=1). ,
, ,
, . . 12.1.

. 12.1.
Instant Domain Search (http://instantdomainsearch.com/).

. , Google ,
, . ,

. . 12.2.

234

. 12.2. Instant Domain Search


, ,
,

del.icio.us

(http://del.icio.us/).

, ,
.
. 12.3.

. 12.3. del.icio.us,
.
, -.
del.icio.us, , ,

Ajax .

, ,
, , ,
. , , . 12.4.

235
. 12.4.


,
.
-. (
) :
: , autocomplete .

, ):

<input type="text" id="to" name="to" autocomplete="off"/>


: , ,
, , :

<img src="indicator.gif" id="qloading"/>


: , ,
. <li>-,
:

<div id="results"><div class="suggest">Suggestions:</div><ul></ul></div>


, JavaScript.
HTML 12.1.
12.1. HTML

<html>
<head>
<script src="dom.js"></script>
<script src="delay.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<form action="" method="POST" id="auto">
<div id="top">
<div id="mhead"><strong>Send Message</strong></div>
<div class="light">
<label>From:</label>
<div class="rest from">
<img src="icons/john_icon.jpg"/>
<strong>John Resig</strong>
</div>
</div>
<div class="query dark">
<label>To:</label>
<div class="rest">

236
<input type="text" id="to" name="to" autocomplete="off"/>
</div>
</div>
<div class="light"><textarea></textarea></div>
<div class="submit"><input type="submit" value="&raquo;
Send"/></div>
</div>
</form>
</body>
</html>
. 12.5 , .

. 12.5. The result of your


form mockup with some simple styling
, ,

, .



, .
.
, .
, ,
:

,
, .

, .
, .


; ; .

237
, , ,
:

,
. , ,
.

(
),
.

,
( , ,
).

. 12.2 ,
. ,
,
( ).
12.2.

function delayedInput(opt) {
//
//
opt.time = opt.time || 400;
// ,
opt.chars = opt.chars != null ? opt.chars : 3;
// , ,
// , , ,
//
opt.open = opt.open || function(){};
// , ,
//
opt.close = opt.close || function(){};
//
// ()
opt.focus = opt.focus !== null ? opt.focus : false;
// ,
//
var old = opt.elem.value;
// -
var open = false;
//

238
setInterval(function(){
//
var newValue = opt.elem.value;
//
var len = s.length;
//
//
if ( old != newValue ) {
// ,
//
if ( v < opt.chars && open ) {
//
opt.close();
// ,
open = false;
// ,
//
} else if ( v >= opt.chars && v > 0 ) {
//
opt.open( newValue, open );
// ,
//
open = true;
}
//
old = newValue;
}
}, opt.time );
//
opt.elem.onkeyup = function(){
// ,
//
if ( this.value.length == 0 ) {
//
opt.close();
// ,
open = false;

239
}
};
// (
// - )
if ( opt.focus ) {
//
opt.elem.onblur = function(){
//
if ( open) {
//
opt.close();
// ,
open = false;
}
}
// ,
//
opt.elem.focus = function(){
// - ,
//
if ( this.value.length != 0 && !open ) {
// ,
//
// ( '' ,
// ,
// ).
opt.open( '', open );
// ,
open = true;
}
};
}
}
12.3 ,
delayedInput.
12.3. delayedInput()

//
delayedInput({
//
elem: id("to"),
//

240
//
chars: 1,
// ,
focus: true,
//
open: function(q,open){
// ,
//
var w = trim( q.substr( q.lastIndexOf(',')+1, q.length ) );
// ,
if ( w ) {
// ,
show( id("qloading") );
//
}
},
//
close: function(){
//
hide( id("results") );
}
});
, ,
,
, -.


,
. Ajax (
);
.
: .
(
). C HTML- (
<li>-), .
12.4 Ajax-, HTML
.
12.4. AJAX- HTML ( )

//

241
ajax({
// GET- CGI-,
// HTML-, LI
type: "GET",
url: "auto.cgi?to=" + w,
// HTML
onSuccess: function(html){
// UL-
results.innerHTML = html;
//
hide( id("qloading") );
// ...
}
});
, 12.4 HTML-
auto.cgi, ,

).

auto.cgi,

Perl, 12.5. ,
HTML-.
12.5. Perl-,

#!/usr/bin/perl
use CGI;
# 'q'
my $cgi = new CGI();
my $q = $cgi->param('to');
# " " ,
# .
my @data = (
{
user => "bradley",
name => "Bradley S"
},
{
user => "jason",
name => "Jason S"
},
{
user => "john",
name => "John R"
},

242
{
user => "josh",
name => "Josh K"
},
{
user => "julia",
name => "Julia W"
}
);
# HTML-
print "Content-type: text/html\n\n";
# ""
foreach my $row (@data) {
# ,
#
if ( $row->{user} =~ /$q/i || $row->{name} =~ /$q/i ) {
# ,
# HTML
print qq~<li id="$row->{user}">
<img src="icons/$row->{user}_icon.jpg"/>
<div>
<strong>$row->{user}</strong> ($row->{name})
</div>
</li>~;
}
}

, CGI- , HTML-, <li>-,


. 12.6 j.
12.6.

HTML,

<li id="jason">
<img src="icons/jason_icon.jpg"/>
<div>
<strong>jason</strong> (Jason S)
</div>
</li><li id="john">
<img src="icons/john_icon.jpg"/>
<div>
<strong>john</strong> (John R)
</div>
</li><li id="josh">

243
<img src="icons/josh_icon.jpg"/>
<div>
<strong>josh</strong> (Josh K)
</div>
</li><li id="julia">
<img src="icons/julia_icon.jpg"/>
<div>
<strong>julia</strong> (Julia W)
</div>
</li>
, , HTML-, HTML,
-, .


, - ,
, .

: .



. ,
, .
, ,
, .
12.7 , .
12.7.

//
id("to").onkeypress = function(e){
//
var li = id("results").getElementsByTagName("li");
// [TAB] [Enter]
if ( e.keyCode == 9 || e.keyCode == 13 ) {
//
//
} else if ( e.keyCode == 38 )
// ,
// )
return updatePos( curPos.previousSibling || li[ li.length - 1 ] );
//
else if ( e.keyCode == 40 )
// , (

244
// )
return updatePos( curPos.nextSibling || li[0] );
};


, ,
.
, <li>, , , <li>
. 12.8 ,
.
12.8. <li>-

// li,
//
li[i].onmouseover = function(){
updatePos( this );
};
// ,
li[i].onclick = function(){
//
addUser( this );
//
id("to").focus();
};
, ,
. .


, :
, , .
. 12.9 JavaScript
.
12.9. JavaScript

domReady(function(){
//
hide( id("results") );
//
var doneUsers = {};
//
var curPos;

245
//
var img = document.createElement("img");
img.src = "indicator.gif";
img.id = "qloading";
//
id("to").parentNode.insertBefore( img, id("to") );
//
var div = document.createElement("div");
div.id = "results";
div.innerHTML = "<div class='suggest'>Suggestions:</div><ul></ul>";
//
id("to").parentNode.appendChild( div );
//
id("to").onkeypress = function(e){
//
var li = id("results").getElementsByTagName("li");
// [TAB] [Enter]
if ( e.keyCode == 9 || e.keyCode == 13 ) {
//
loadDone();
//
// ,
if ( !doneUsers[ curPos.id ] )
addUser( curPos );
//
e.preventDefault();
return false;
//
} else if ( e.keyCode == 38 )
// ,
// )
return updatePos( curPos.previousSibling ||
li[ li.length - 1 ] );
//
else if ( e.keyCode == 40 )
// ,
// )
return updatePos( curPos.nextSibling || li[0] );

246
};
//
delayedInput({
//
elem: id("to"),
//
//
chars: 1,
// ,
//
focus: true,
//
open: function(q,open){
// ,
//
var w = trim( q.substr( q.lastIndexOf(',')+1, q.length ) );
// ,
if ( w ) {
// ,
show( id("qloading") );
// ,

curPos = null;
// UL,
//
var results = id("results").lastChild;
//
results.innerHTML = "";
//
ajax({
// GET-
// CGI-,
// HTML- LI-
type: "GET",
url: "auto.cgi?q=" + w,
// HTML
onSuccess: function(html){
// UL
results.innerHTML = html;

247
//
hide( id("qloading") );
//
//
loadDone();
//
//
var li = results.getElementsByTagName( "li" );
for ( var i = 0; i < li.length; i++ ) {
// ,
// LI
if ( doneUsers [ li[i].id ] )
results.removeChild( li[i--] );
// li
//
else {
//
// li,
//
//
li[i].onmouseover = function(){
updatePos( this );
};
//
li[i].onclick = function(){
//
addUser( this );
//
id("q").focus();
};
}
}
//
li = results.getElementsByTagName( "li" );
// ( )
if ( li.length == 0 )
//
hide( id("results") );

248
else {
//
//
// 'odd',
//
for ( var i = 1; i < li.length; i += 2 )
addClass( li[i], "odd" );
//
//
updatePos( li[0] );
//
show( id("results") );
}
}
});
}
},
//
close: function(){
//
hide( id("results") );
}
});
function trim(s) {
return s.replace(/^\s+/,"").replace(/\s+$/, "");
}
//
function updatePos( elem ) {
//
curPos = elem;
// li-
var li = id("results").getElementsByTagName("li");
// 'cur'
for ( var i = 0; i < li.length; i++ )
removeClass( li[i], "cur" );
//
//
addClass( curPos, "cur" );

249
return false;
}
// ,
//
function loadDone() {
doneUsers = {};
// ( )
var users = id("q").value.split(',');
for ( var i = 0; i < users.length; i++ ) {
// ( )
// -
doneUsers[ trim( users[i].toLowerCase() ) ] = true;
}
}
//
function addUser( elem ) {
//
var v = id("to").value;
// ,
//
id("to").value =
( v.indexOf(',') >= 0 ? v.substr(0, v.lastIndexOf(',') + 2 ) : '' )
+ elem.id + ", ";
//
// ( )
doneUsers[ elem.id ] = true;
// li-
elem.parentNode.removeChild( elem );
//
hide( id("results") );
}
});
. 12.6 , .

250

. 12.6.

.
,
.

.
.

. , ,
,
. , ,
, .
,
- http://www.jspro.org/.
Source Code/Download - Apress http://www.apress.com.

251

1 3 Ajax Wiki
- ,
-- MVC ( Ruby on Rails Django), ,
, . , wiki.

Wiki?
Wikipedia.org (, -, wiki), wiki -, ,
, , .
wiki
.
wiki-
. . 13.1 wiki ,
.
, wiki
JavaScript, JavaScript .
, -,
, .
: , (
Ajax-), .
.
.
, , ,
, , ,
.

252

. 13.1. , wiki


wiki - . , -
, . ,
,
. , JavaScript, ,
- ,
wiki. . 13.2 , .
(, SELECT, INSERT ..).
. -,
. -,
. , ,
, JavaScript-.

( . 13.2) , JavaScript .

253

. 13.2. ,

, SQL- ;
, . -
SQL- ,
. ,
.
, ,

JavaScript .

Ajax-
Ajax- (, , ).
, Ajax- , , wiki.
:
wiki-: wiki-
CamelCase ( ), ,
. , wiki HomePage.
: , . , ,
( wiki-).
: , .
Textile.

. ,
.
, , , .
, 13.1.
13.1. , , ,

//
sqlExec(
// ,

254
"insert",
[
document.title, //
$("#author").val(), // ,
$("#text").val(), //
(new Date()).getTime() //
],
//
reload
);
sqlExec SQL- (
CGI-), URL , Ajax-.
Ajax- jQuery, HTTP POST-
(POST- ). Ajax-
JSON-.
, ,
.


.
SQL-, SQL
JSON-. ,
: Perl, PHP, Python Ruby.
, ; ,
.


,
SQL- . ,
, CGI-, .
, : SQL. , , 13.2 ,
, Ruby.
13.2. CGI-, , Ruby

# CGI-
require 'cgi'
# CGI-,
# CGI-
cgi = CGI.new
#
sql = cgi['sql']
# ,

255
#
#
d = cgi['db'].gsub(/[^a-zA-Z0-9_-]/, "")
, , ,
, .
SQL ( -).
SQL SQLite.
SQLite SQL,
.
, , .
. SQLite , ,
, . , SQLite
. SQLite , ,
( MySQL, PostgreSQL Oracle).
(Perl, PHP, Python Ruby) SQLite:

Perl DBD::SQLite. ,
SQLite , ,
.

PHP 5 SQLite. SQLite 2 (


),
, PHP SQLite 3.

Python Ruby SQLite,


SQLite. Python 2.5 SQLite, ( ).
, -

SQLite. ,
.
SQLite .
: -, SQLite (
), -,
.
13.3 , Ruby.
13.3. SQLite Ruby-

# SQLite-
require 'rubygems'
require_gem 'sqlite3-ruby'
# ;
# 'd' , ,
#

256
d = cgi['db'].gsub(/[^a-zA-Z0-9_-]/, "")
# SQLite,
# 'd' 'wiki'
db = SQLite3::Database.new('../../data/' + d + '.db')
, SQLite, ,
, .

SQL
, , SQL-.
,
JSON- . SQL- ,
, 13.4.
. - .
13.4. JSON-,

[
{
title: "HomePage",
author: "John",
content: "Welcome to my wonderful wiki!",
date: "20060324122514"
},
{
title: "Test",
author: "Anonymous",
content: "Lorem ipsum dolem;",
date: "20060321101345"
},
. . .
]
SQL-
. SQL- : ,
, (. 13.5).
13.5. , SQL-
, Wiki, Ruby

rows.columns = ["title","author","content","date"]
rows = [
["HomePage","John","Welcome to my wonderful wiki!","20060324122514"],
["Test","Anonymous","Lorem ipsum dolem;","20060321101345"],
. . .
]

257
SQL-, 13.5,
, 13.4, . ,
, ,
, . 13.6 ,
Ruby.
13.6.

Ruby

SQL-,

( r)

# sql (, SELECT)
db.query( sql ) do |rows|
#
rows.each do |row|
#
tmp = {}
# -
for i in 0 .. rows.columns.length-1
tmp[rows.columns[i]] = row[i]
end
#
r.push tmp
end
end
, ,
JSON. , JSON ( ),
( -), JavaScript- .
, , ,
JSON-.
, , JSON-
( JSON-), , ,
. , , ,
JSON, . ,
, :

(, , ).

JSON.
Ruby JSON- .

JSON- ( JSON) :

# (r) JSON-,
print r.to_json
,
, SQL- JSON-. ,
, .

258
JSON-
, , JSON-.
13.2 , JSON. JSON, .
( XML); , eval() (
JavaScript, , , JSON-). 13.7 ,
jQuery, . ,
( dataType) json, JSON- .
13.7. JavaScript

//
$.ajax({
// POST API URL
type: "POST",
url: apiURL,
//
data: $.param(p),
// JSON
dataType: "json",
//
// ,
//
success: callback
});
, 13.7
callback ( ,
sqlExec). , ,
. ,
sqlExec-Ajax-, 13.8 ,
wiki. , ,
. , ,
.
13.8. ,
-

// wiki-
// 'loaded'
sqlExec("select", [$s], loaded);
// SQL-,
function loaded(sql) {
// wiki
if ( sql.length > 0 ) {

259
// wiki-
showContent();
// textile
$("#content").html(textile(sql[0].content));
//
$("textarea").val( sql[0].content );
// , 'create me'
} else {
//
showForm();
}
}
, 13.8, textile(sql[0].content),
wiki-
Textile. HTML , Textile.
, , . Textile . 13.3.

. 13.3. Wiki-, Textile-


Textile , - ,
Textile JavaScript, Textile ,
HTML. Textile -:

Textile: http://www.textism.com/tools/textile/

JavaScript- Textile ( ): http://jrm.cc/extras/live-textile-preview.php


, ,

wiki-.
wiki- . ,
, - .

: JavaScript
, --SQLite,
, .
, . ;
,
. , SQL-,

260
. - (http://jspro.org/). . 13.4.

. 13.4. SQL-

. ,
( , ).
, wiki-.
, ,
, :

index.html: , .

install.html: ,
.

css/style.css: CSS- .

js/wiki.js (. 13.9): JavaScript, SQL.

js/sql.js (. 13.10): , , JSON-,


SQL-.

js/textile.js: JavaScript Textile ( HTML):


http://jrm.cc/extras/live-textile-preview.php.

261

js/jquery.js: jQuery: http://jquery.com/.

api/: , SQL- JSON


. : Perl, PHP, Python Ruby.
Ruby- 13.11.

data/wiki.db: SQLite, wiki.


.

JavaScript

13.9

wiki.js,

JavaScript,

.
13.9. js/wiki.js

//
var $s = window.location.search;
$s = $s.substr(1,$s.length);
// , ,
// , ID
var $r = false;
//
// ?Title&RevisionID
var tmp = $s.split("&");
if ( tmp.length > 1 ) {
$s = tmp[0];
$r = tmp[1];
}
// ,
if (!$s) window.location = "?HomePage";
//
var db = "wiki";
// DOM
$(document).ready(function(){
//
document.title = $s;
$("h1").html($s);
// wiki-
reload();
//
// 'edit page' ( )
$("#edit").click(showForm);

262
//
$("#post form").submit(function(){
//
var author = $("#author").val();
//
var text = $("#text").val();
//
$("#content").html(textile(text));
//
// ( )
$r = (new Date()).getTime();
//
sqlExec("insert", [$s,author,text,$r], reload);
return false;
});
// 'cancel' ()
//
$("#cancel").click(showContent);
});
//
function showContent() {
//
$("#edit,#cancel").css("display","inline");
//
$("#post").hide();
//
$("#content").show();
return false;
}
//
function showForm() {
//
$("#edit").hide();
//
$("#post").show();

263
//
$("#content").hide();
return false;
}
//
function reload(t) {
//
sqlExec("select", [$s], function(sql) {
// wiki-
if ( sql.length > 0 ) {
if ( !$r ) $r = sql[0].date;
// wiki-
showContent();
//
$("#side ul").html('');
//
for ( var i = 0; i < sql.length; i++ ) {
//
if ( sql[i].date == $r ) {
//
$("#content").html(textile(sql[i].content));
//
//
$("textarea").val( sql[i].content );
}
//
var d = new Date( parseInt(sql[i].date) );
// ,
// ,
if ( d.getTime() > (new Date()).getTime() - (3600 * 24000) )
// ,
// am/pm
d = d.getHours() >= 12 ?
(d.getHours() != 12 ? d.getHours() - 12 : 12 )
+ " pm" :
d.getHours() + " am";

264
//
//
else {
var a = d.toUTCString().split(" ");
d = a[2] + " " + d.getDate();
}
//
$("#side ul").append("<li class='" +
( $r == sql[i].date ? "cur" : "" )
+ "'><a href='?" + $s + ( i > 0 ? "&"
+ sql[i].date : "" )
+ "'>" + d + "</a> by " + sql[i].author + "</li>");
}
//
} else {
//
$("#rev").html("<li>No Revisions.</li>");
//
$("#edit,#cancel").hide();
//
showForm();
}
});
}

JavaScript SQL-
13.10 sql.js, ,
JSON-, SQL-.
13.10. js/sql.js

//
// URL,
var apiURL = "api/ruby/";
//
var sqlLoaded = function(){}
// SQL-
//
// (, INSERT),
// ,
function sqlExec(q, p, callback) {
//

265
for ( var i = 0; i < p.length; i++ ) {
p[i] = { name: "arg", value: p[i] };
}
//
p.push({ name: "db", value: db });
// SQL-,
p.push({ name: "sql", value: q });
//
$.ajax({
// POST API URL
type: "POST",
url: apiURL,
//
data: $.param(p),
// JSON
dataType: "json",
//
// ,
//
success: callback
});
}

Ruby-
, 13.11, Ajax- wiki-.
Ruby. , PHP,
Perl Python, - http://jspro.org/.
13.11. wiki-, Ruby

#!/usr/bin/env ruby
#
require 'cgi'
require 'rubygems'
require_gem 'sqlite3-ruby'
require 'json/objects'
# Javascript
print "Content-type: text/javascript\n\n"
#
err = ""

266
r = []
cgi = CGI.new
# ,
call = cgi['callback']
sql = cgi['sql']
# ,
#
#
d = cgi['db'].gsub(/[^a-zA-Z0-9_-]/, "")
# , 'test'
if d == '' then
d = "test"
end
# ,
# SQL-
args = cgi.params['arg']
# SQL-
# wiki-
if sql == "insert" then
sql = "INSERT INTO wiki VALUES(?,?,?,?);"
# wiki-
elsif sql == "select" then
sql = "SELECT * FROM wiki WHERE title=? ORDER BY date DESC;"
# ,
else
sql = ""
end
#
if sql != '' then
#
for i in 0 .. args.length-1
# '' (
# SQLite), ?
args[i] = args[i].gsub(/'/, "''").gsub(/\?/, "\\?")
# SQL-
#
sql = sql.sub(/([^\\])\?/, "\\1'" + args[i] + "'")

267
end
# , ,
sql = sql.gsub(/\\\?/, "?")
#
begin
# SQLite,
#
db = SQLite3::Database.new('../../data/' + d + '.db')
# sql
# (, SELECT)
db.query( sql ) do |rows|
#
rows.each do |row|
#
tmp = {}
#
# -
for i in 0 .. rows.columns.length-1
tmp[rows.columns[i]] = row[i]
end
#
r.push tmp
end
end
rescue Exception => e
# ,
#
err = e
end
else
# SQL- ,
err = " ."
end
# , ,
# error ,
if err != '' then
r = { "error" => err }
end
# JSON-
jout = r.to_json

268
#
if call != '' then
#
print call + "(" + jout + ")"
else
# JSON-
print jout
end

, . -,
JSON XML -. -,

(
, ). ,
,
( )
(
).
.
- http://jspro.org/, -
http://www.apress.com/, .
: http://jspro.org/demo/wiki/.
- . ,
,
.

269

1 4 JavaScript?

JavaScript. Mozilla Foundation JavaScript,
ECMAScript 4 (, JavaScript). WHATWG,

-,

,
, . ,

Comet. JavaScript .
, JavaScript 1.6 1.7,
JavaScript 2.0. ,
Web Applications 1.0: JavaScript.
, Comet -.

JavaScript 1.6 1.7


JavaScript ,
. JavaScript 1.5 (
), .
(Brendan Eich) Mozilla Foundation,
ECMAScript 4. Mozilla
:

Mozilla JavaScript: http://www.mozilla.org/js/language/

Mozilla JavaScript 2.0: http://www.mozilla.org/js/language/js20/

Mozilla ECMAScript 4: http://www.mozilla.org/js/language/es4/


JavaScript 2.0, Mozilla JavaScript 1.6 1.7,

, , .
, .

JavaScript 1.6
JavaScript JavaScript 1.6.
Firefox 1.5, Mozilla Foundation. , JavaScript 1.6
- Mozilla: http://developer.mozilla.org/en/docs/New_in_JavaScript_1.6.
: E4X (ECMAScript XML)
.
, , Opera Safari , .
.

ECMAScript XML (E4X)


E4X JavaScript ,
XML JavaScript. ,
. E4X - Mozilla:

ECMAScript XML: http://www.ecma-international.org/publications/standards/Ecma-357.htm

270

E4X: http://developer.mozilla.org/presentations/xtech2005/e4x/
, JavaScript- ,

XML DOM. , writing var img = <img/> + <hr/>,


, DOM-
, . 14.1.
XML- 14.2.
14.1. HTML- E4X,

<script type="text/javascript;e4x=1">
// HTML-
var html = <html/>;
// title
// E4X
//
html.head.title = " ";
// body,
//
html.body.@bgcolor = "#e4e4e4";
// form body
html.body.form.@name = "myform";
html.body.form.@action = "someurl.cgi";
html.body.form.@method = "post";
html.body.form.@onclick = "return somejs();";
// input
html.body.form.input[0] = "";
html.body.form.input[0].@name = "test";
</script>
14.2. HTML-, E4X- 14.1

<html>
<head>
<title> </title>
</head>
<body bgcolor="#e4e4e4">
<form name="myform" action="someurl.jss"
method="post" onclick="return somejs();">
<input name="test"></input>
</form>
</body>
</html>

271
E4X JavaScript
, ,
DOM-.


, JavaScript 1.6, .
1.6 ,
:

, indexOf() lastIndexOf(), ,
. ,
, -1, .

, forEach(), some() many(), ,


, .

filter() map() ,
map grep, (, Perl).
JavaScript 1.6

14.3.
14.3. JavaScript 1.6,

//
var tmp = [ 1, 2, 3, 4, 5, 3 ];
// indexOf( )
//
tmp.indexOf( 3 ) == 2
tmp.indexOf( 8 ) == -1
// lastIndexOf( )
//
tmp.lastIndexOf( 3 ) == 5
// forEach( )
// .
// : ,
tmp.forEach( alert );
// every( )
// ,
// true, true
tmp.every(function(num){
return num < 6;
}) // true
// some( )

272
// .
// - true,
// true
tmp.some(function(num){
return num > 6;
}) // false
// filter( )
// ,
// . , 'true'.
tmp.filter(function(num){
return num > 3;
}) // [ 4, 5 ]
// map( )
// . ,
// ,
//
tmp.map(function(num) {
return num + 2;
}) // [ 3, 4, 5, 6, 7, 5 ]
, JavaScript
. ,
.

JavaScript 1.7
JavaScript ,
, . ,
JavaScript 1.7, ,
JavaScript 1.6, , .

JavaScript 1.7,

http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7.
JavaScript Mozilla Firefox 2.0.
, ,
, JavaScript.


,
. , ,
.
, , , , 14.4.
14.4. JavaScript 1.7

<script type="application/javascript;version=1.7">
//
var array = [];

273
for ( var i = 0; i < 10; i++ ) {
array.push( i );
}
//
var array = [ i for ( i = 0; i < 10; i++ ) ];
//
var array = []
for ( var key in obj ) {
array.push( key );
}
//
var array = [ key for ( key in obj ) ];
</script>
(
Python), , JavaScript.

(Let Scoping)
Let Scoping

. JavaScript (
2). let-,
. 14.5
, let scoping.
14.5. Let Scoping JavaScript 1.7

<script type="application/javascript;version=1.7">
// let
var test = 10;
let( test = 20 ) {
alert( test ); // 20
}
alert( test ); // 10
// let
var test = 10;
alert( let( test = 20 ) test ); // 20
alert( test ); // 10
// let
var test = 10;
if ( test == 10 ) {
let newTest = 20;
test += newTest;
}
alert( test ); // 30

274
alert( newTest ); // , newText
//

// let for
for ( let i = 0; i < 10; i++ ) {
alert( i );
}
alert( i ); // , i for
//
</script>
,
, (
JavaScript 2.0).

JavaScript 1.7,

(destructuring). ( , Lisp),
, .
ECMAScript 4 - Mozilla: http://
developer.mozilla.org/es4/proposals/destructuring_assignment.html.
,
. 14.6
JavaScript 1.7.
14.6. 1.7

<script type="application/javascript;version=1.7">
//
//
[ b, a ] = [ a, b ]
// ,
function test() {
return [ "", "" ];
}
//
// name month
var [ name, month ] = test();
//
var { name: myName } = { name: "" };
// myName == ""
//
var users = [
{ name: "", month: "" },

275
{ name: "", month: "" },
{ name: "", month: "" }
];
//
for ( let { name: name, month: month } in users ) {
// ,
alert( name + " " + month );
}
</script>
JavaScript ,
( Python Lisp).
,
. , Mozilla Foundation
, . JavaScript 1.6
1.7 - ,
, Mozilla (
, ).

Web Applications 1.0


, JavaScript- Web Applications 1.0,
WHAT-WG (Web Hypertext Application Technology Working Group).
, HTML, DOM JavaScript
. , HTML 5. ,
JavaScript, ( ) .
,
, .
: <canvas>.
, JavaScript.
, . Web
Applications 1.0 <canvas> :

Web Applications 1.0: http://whatwg.org/specs/web-apps/ current-work/

, <canvas>: http://whatwg.org/specs/webapps/current-work/#the-2d

<canvas>: http://developer.mozilla.
org/en/docs/Canvas_tutorial:Basic_animations
<canvas> -,

, .
- .
,
, Canvas API .
, Internet Explorer, Canvas API, Google
, Canvas API IE, VML.
ExplorerCanvas, Google Canvas Internet Explorer
: http://code.google.com/p/explorercanvas/.

276
,
Mozilla <canvas>.


. Canvas 2D API
; -
HTML-. . 14.1 , .

. 14.1. , Canvas API


<canvas> .
, ,
. OpenGL API,
Canvas API.
Canvas API, ,
, , ,
. Canvas API :
, -
, .
14.7 ,
Canvas; , - Canvas.
14.7. Canvas API

<html>
<head>
<title> Canvas </title>
<script>
//
window.onload = function() {
//
clock();
//
setInterval(clock, 1000);
};
function clock() {
//
var now = new Date();
var sec = now.getSeconds();

277
var min = now.getMinutes();
var hr = now.getHours();
hr = hr >= 12 ? hr - 12 : hr;
// <canvas>
var ctx = document.getElementById('canvas').getContext('2d');
ctx.save();
//
ctx.clearRect(0,0,150,150);
// 0,0, 75,75
ctx.translate(75,75);
// 100px, 40px
ctx.scale(0.4,0.4);
// 12:00
ctx.rotate(-Math.PI/2);
//
ctx.strokeStyle = "black";
ctx.fillStyle = "black";
ctx.lineWidth = 8;
ctx.lineCap = "round";
//
ctx.save();
ctx.beginPath();
//
for ( var i = 0; i < 12; i++ ) {
// 1/12
// (: = 2 * PI)
ctx.rotate(Math.PI/6);
//
ctx.moveTo(100,0);
// (20px)
ctx.lineTo(120,0);
}
ctx.stroke();
ctx.restore();
//
ctx.save();
//
ctx.lineWidth = 5;

278
ctx.beginPath();
//
for ( var i = 0; i < 60; i++ ) {
// ,
if ( i % 5 != 0 ) {
//
ctx.moveTo(117,0);
// (3px)
ctx.lineTo(120,0);
}
// 1/60
ctx.rotate(Math.PI/30);
}
ctx.stroke();
ctx.restore();
//
ctx.save();
//
ctx.rotate( (Math.PI/6) * hr + (Math.PI/360) * min
+ (Math.PI/21600) * sec )
//
ctx.lineWidth = 14;
ctx.beginPath();
// (
// )
ctx.moveTo(-20,0);
//
ctx.lineTo(80,0);
ctx.stroke();
ctx.restore();
//
ctx.save();
//
ctx.rotate( (Math.PI/30) * min + (Math.PI/1800) * sec )
// ,
ctx.lineWidth = 10;
ctx.beginPath();
// ,

279
//
ctx.moveTo(-28,0);
//
ctx.lineTo(112,0);
ctx.stroke();
ctx.restore();
//
ctx.save();
//
ctx.rotate(sec * Math.PI/30);
//
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
// ,
ctx.lineWidth = 6;
ctx.beginPath();
//
ctx.moveTo(-30,0);
//
ctx.lineTo(83,0);
ctx.stroke();
ctx.restore();
//
ctx.save();
//
ctx.lineWidth = 14;
//
ctx.strokeStyle = '#325FA2';
ctx.beginPath();
// ,
// 142px
ctx.arc(0,0,142,0,Math.PI*2,true);
ctx.stroke();
ctx.restore();
ctx.restore();
}
</script>
</head>

280
<body>
<canvas id="canvas" height="150" width="150"></canvas>
</body>
</html>
(
, ), Canvas 2D API
.



. : ,
. ( , ),
, .
, . . 14.2 ,
.

. 14.2. ,

Canvas
, , ( ,
), ,
. 14.8 ,
Canvas.
14.8. , Canvas 2D API

<html>
<head>
<title> Canvas</title>
<script>
//
var imgs = { sun: null, moon: null, earth: null };
//

281
window.onload = function() {
//
for ( var i in imgs )
imgs[i] = document.getElementById(i);
// 10
setInterval( draw, 100 );
};
function draw() {
//
var time = new Date();
var s = ( (2 * Math.PI) / 6) * time.getSeconds();
var m = ( (2 * Math.PI) / 6000 ) * time.getMilliseconds();
// <canvas>
var ctx = document.getElementById('canvas').getContext('2d');
//
ctx.clearRect(0,0,300,300);
// ( )
// :
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Compositing
ctx.globalCompositeOperation = 'destination-over';
ctx.save();
//

0,0 = 150,150

ctx.translate(150,150);
//
ctx.rotate( (s + m) / 10 );
// 105
ctx.translate(105,0);
// ( ,
// )
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
// (
// , )
ctx.fillRect(0,-12,50,24);
//
ctx.drawImage(imgs.earth,-12,-12);
ctx.save();

282
// ,
ctx.rotate( s + m );
// ' '
ctx.translate(0,28.5);
//
ctx.drawImage(imgs.moon,-3.5,-3.5);
ctx.restore();
ctx.restore();
//
ctx.beginPath();
ctx.arc(150,150,105,0,Math.PI*2,false);
ctx.stroke();
//
ctx.drawImage(imgs.sun,0,0);
}
</script>
</head>
<body style="background:#000;">
<canvas id="canvas" height="300" width="300"></canvas>
<!-- -->
<div style="display:none;">
<img src="sun.png" id="sun"/>
<img src="moon.png" id="moon"/>
<img src="earth.png" id="earth"/>
</div>
</body>
</html>
<canvas> API ;
Apple, Opera.
JavaScript ,
.

Comet

. Ajax
( ),
- . ,
, -, Comet (
(Alex Russell) Dojo). -
, (, ).
Ajax, Comet, , .
, -

283
, Cometd. Cometd
Comet :

(Alex Russell), , Comet:


http://alex.dojotoolkit.org/?p=545

Comet: http://cometd.com/
Comet Ajax- ,

.
. . 14.3 ,
Comet Ajax-.

Dojo

Foundation

Comet ,
-. 14.9 Dojo Comet ( Cometd).
14.9. Dojo Cometd

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> - Cometd</title>
<script type="text/javascript">
//
//
djConfig = { isDebug: true };
</script>
<script type="text/javascript" src="../dojo/dojo.js"></script>
<script type="text/javascript">
dojo.require("dojo.io.cometd");
dojo.addOnLoad(function(){
// URL cometd
cometd.init({}, "/cometd");
//
// ,
//
cometd.subscribe("/foo/bar/baz", false, dojo, "debugShallow");
//
cometd.publish("/foo/bar/baz", { thud: "thonk!"});
cometd.publish("/foo/bar/baz/xyzzy",
{ foo: "A simple message" });
});
</script>

284
</head>
<body></body>
</html>
, Comet ( Comet )
, ,
, .

285

. 14.3. Ajax -,
Comet

286
, , , ,
( JavaScript 1.7),
(, <canvas>). ,
, -,
.

287

DOM
,
, 5.

Resources
DOM ,
DOM Level 0, DOM Levels 1 2.
W3C DOM Levels
1 2, - W3C DOM:

DOM Level 1: http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html

HTML DOM Level 1: http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html

DOM Level 2: http://www.w3.org/TR/DOM-Level-2-Core/

HTML DOM Level 2: http://www.w3.org/TR/DOM-Level-2-HTML/


DOM,

, Quirksmode.org, -, -
(Peter-Paul Koch). DOM-
( ). ,
, , :

W3C DOM Core Levels 1 and 2 reference: http://www.quirksmode.org/dom/w3c_core.html

W3C DOM HTML Levels 1 and 2 reference: http://www.quirksmode.org/dom/w3c_html.html

5, , ,
XML DOM DOM- XML-.
, , ,
XML. HTML-,
A.1.
A.1. , DOM XML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Introduction to the DOM</title>
</head>
<body>
<h1>Introduction to the DOM</h1>
<p class="test">There are a number of reasons why the DOM is awesome,
here are some:</p>
<ul>
<li id="everywhere">It can be found everywhere.</li>
<li class="test">It's easy to use.</li>

288
<li class="test">It can help you to find what you want, really
quickly.</li>
</ul>
</body>
</html>

, , ,
, .. .1 <ul>
<body> <html>.

,
. .1 <p> class, test.


(
). .1 <ul> ;
<li>, ,
( ).

Document
XML- (
document), . .1 document
<html>, .

, , .. .1
<body> <h1>, <p>, <ul> <li>-, ,
.

, .
HTML- . .1
; <html>, <head>, <title>, <body>, <h1>, <p>, <ul> <li>

DOM-. , , ,
, (
, nodeType, nodeName nodeValue ).

, .
, . .1 <p> <body>.

289

.
previousSibling nextSibling, , DOM-. .1
<p> <h1> <ul> (
).


, ;
. (, <b>hello world!</b>), ,
<b> , hello world!.
Its easy to use .1, <li>,
.

DOM-.

document
HTML DOM-, .
- ,
.
DOM 5. .2
document, HTML DOM .
A.2. document

// , ID 'body'
document.getElementById("body")
// , <div>.
document.getElementsByTagName("div")

HTMLElement
HTML DOM-.
HTML DOM-.
Mozilla Opera. , 5,
Internet Explorer Safari. .3
HTMLElement. hasClass ,
.
A.3. HTMLElement

// HTML DOM- ,
// ,
// .
HTMLElement.prototype.hasClass = function( class ) {

290
return new RegExp("(^|\\s)" + class + "(\\s|$)").test( this.className );
};

DOM
DOM-
DOM-.

body
HTML DOM- ( document)
HTML- <body> ( ). ,
DOM 0 JavaScript. .4
<body> HTML DOM-.
A.4. <body> HTML DOM-

// <body>
document.body.style.margin = "0px";
// document.body :
document.getElementsByTagName("body")[0]

childNodes
DOM- ( ,
, ..). . .5 ,
childNodes
.
A.5. ,
<body> childNodes

// ,

<body>

var c = document.body.childNodes;
for ( var i = 0; i < c.length; i++ ) {
// ,
if ( c[i].nodeType == 1 )
c[i].style.border = "1px solid red";
}

documentElement
, DOM-,
( HTML-, <html>). .6
documentElement DOM-.
A.6. DOM-

// documentElement ID

291
.documentElement.getElementById("body")

firstChild
, DOM-, .
, firstChild . .7
firstChild .
A.7.

//
var e = document.getElementById("body");
while ( e.firstChild )
e.removeChild( e.firstChild );

getElementById( ID )
, ,
ID. document. , ,
DOM-, HTML; , XML DOM ID DTD ( Document Type Definition)
.
.8, : ID.
A.8. HTML- ID-

// ID, body
document.getElementById("body")
// , ID notice
document.getElementById("notice").style.display = 'none';

getElementsByTagName( )
-, ,
. XML DOM, HTML DOM-.
(*)
-, , ,
JavaScript.
: . .9
getElementsByTagName. highlight <div>-
. , ID body,
, highlight.
A.9. , getElementsByTagName

292
// <div> HTML-
// class 'highlight'
var d = document.getElementsByTagName("div");
for ( var i = 0; i < d.length; i++ ) {
d[i].className = 'hilite';
}
// - ,
// ID body. ,
// class 'hilite'. ,
// .
var all = document.getElementById("body").getElementsByTagName("*");
for ( var i = 0; i < all.length; i++ ) {
if ( all[i].className == 'hilite' )
all[i].style.display = 'none';
}

lastChild
, DOM-, .
, lastChild (null). .10
lastChild .
A.10. <div>- <body>

//
// <body>
var n = document.createElement("div");
n.innerHTML = " !";
document.body.insertBefore( n, document.body.lastChild );

nextSibling
, DOM-, .
, nextSibling (null). ,
nextSibling DOM-, ;
DOM-. .11
nextSibling .
A.11. <dt> <dd>

// <dt> (Defintion Term )


var dt = document.getElementsByTagName("dt");
for ( var i = 0; i < dt.length; i++ ) {
//
dt[i].onclick = function() {

293
//
// <dd> (Definition ),
//
// : , <dd>
//
this.nextSibling.style.display = 'block';
};
}

parentNode
DOM-. parentNode DOM- ,
, document, null (
). .12 parentNode
. Cancel ()
.
A.12. parentNode

// (, Cancel)
//
document.getElementById("cancel").onclick = function(){
this.parentNode.style.display = 'none';
};

previousSibling
, DOM-, .
, previousSibling (null). ,
previousSibling DOM-, ;
DOM-. .13
previousSibling .
A.13.

// ,
var cur = this.previousSibling;
while ( cur != null ) {
cur.style.display = 'none';
cur = this.previousSibling;
}


DOM-
.

innerText

294
DOM- ( ,
Mozilla, W3C). ,
, .
Mozilla, ,
5 ( -). .14
innerText text() 5.
A.14. innerText

// , <li> ,
// 'li':
// <li>, <a href="http://mysite.com/">
- </a>.</li>
// innerText
li.innerText
// text(), 5
text( li )
// :
", -."

nodeName
DOM-, .
, <li>, nodeName, LI.
.15 nodeName .
A.15. <li> current

// , <li>
var cur = this.parentNode;
while ( cur != null ) {
// ,
if ( cur.nodeName == 'LI' )
cur.className += " current";
cur = this.parentNode;
}

nodeType
DOM-, , .
, HTML-:

( 1 document.ELEMENT_NODE)

( 3 document.TEXT_NODE)

( 9 document.DOCUMENT_NODE)

295
nodeType , ,
, ( , nodeName
DOM-t; nodeType,
, 1). .16 nodeType
.
A.16. HTML <body> header

// <body>
var cur = document.body.firstChild;
while ( cur != null ) {
// , header
if ( cur.nodeType == 1 ) {
cur.className += " header";
cur = null;
//
} else {
cur = cur.nextSibling;
}
}

nodeValue
, ,
. text,
5, . .17
nodeValue .
A.17. ,
-

function text(e) {
var t = "";
// , ,
// , ,
e = e.childNodes || e;
//
for ( var j = 0; j < e.length; j++ ) {
// , ,
//
//
t += e[j].nodeType != 1 ?
e[j].nodeValue : text(e[j].childNodes);
}

296
//
return t;
}

. , ID
element.id. DOM 0,
, .

className
DOM-.
DOM. className,
. , class ; ,
-. .18 className
.
A.18. <div>-, special

// <div>
var div = document.getElementsByTagName("div");
for ( var i = 0; i < div.length; i++ ) {
// <div>, 'special'
if ( div[i].className == "special" ) {
//
div[i].style.display = 'none';
}
}

getAttribute( )
, DOM. , HTML.
: , .
.19 getAttribute() input
.
A.19. <input>, name text
, ID preview

// input
var input = document.getElementsByTagName("input");
for ( var i = 0; i < input.length; i++ ) {
// , name "text"
if ( input[i].getAttribute("name") == "text" ) {

297
//
document.getElementById("preview").innerHTML =
input[i].getAttribute("value");
}
}

removeAttribute( )
.
setAttribute " "
( ) null; ,
.
: , . .20
.
A.20. , ,

//
var input = document.getElementsByTagName("input");
for ( var i = 0; i < input.length; i++ ) {
//
if ( input[i].getAttribute("type") == "checkbox" ) {
//
input[i].removeAttribute("checked");
}
}

setAttribute( attrName, attrValue )


, DOM. , ,
DOM-. setAttribute Internet Explorer
, (, class
maxlength). 5.
. , .
.21 DOM-.
A.21. setAttribute <a>- Google

// <a>
var a = document.createElement("a").
// URL - Google
a.setAttribute("href","http://google.com/");

298
// ,
//
a.appendChild( document.createTextNode( " Google!" ) );
//
document.body.appendChild( a );

DOM
, DOM.

appendChild( )
-.
,
. appendChild , .
: DOM- ( ,
, - ). .22
<ul> <li>-
DOM, <ul> .
A.22. <li>- <ul>

// <ul>
var ul = document.createElement("ul");
// <li>
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
// <li>
// <ul>
ul.appendChild( li[i] );
}
// <ul> body
document.body.appendChild( ul );

cloneNode( true|false )

, DOM. insertBefore
appendChild DOM- , cloneNode
.
true false. true,
; false, . .23
.

299
A.23. <ul>,

// <ul>
var ul = document.getElementsByTagName("ul")[0];
//
ul.parentNode.appendChild( ul.cloneNode( true ) );

createElement( )
, DOM-.
, .

XHTML, (content-type) application/xhtml+xml,


HTML, text/html, createElement
createElementNS.
: . .24
.
A.24. <p> <strong>

// <strong>
var s = document.createElement("strong");
//
var p = document.getElementsByTagName("p")[0];
// <p> <strong>
while ( p.firstChild ) {
s.appendChild( p.firstChild );
}
// <strong> ( <p>)
// <p>
p.appendChild( s );

createElementNS( _, )
createElement, ,
(, ,
XML XHTML).
: , .
.25 DOM- XHTML.

300
A.25. XHTML <p>-,

// XHTML- <p>
var p = document.createElementNS("http://www.w3.org/1999/xhtml", "p");
// <p>
p.appendChild( document.createTextNode( "Welcome to my site." ) );
// <p>
document.body.insertBefore( p, document.body.firstChild );

createTextNode( )
DOM-.
DOM , ,
. DOM-.
: , . .26
HTML.
A.26. <h1>

// <h1>
var h = document.createElement("h1");
// <h1>
h.appendChild( document.createTextNode(" ") );
// <body>
document.body.insertBefore( h, document.body.firstChild );

innerHTML
, HTML DOM, HTML DOM- . HTML- (
XML), , ,
DOM-, ( ,
DOM-). W3C-,
.
.27 innerHTML
<textarea>.
A.27. <textarea>

// textarea

301
var t = document.getElementsByTagName("textarea")[0];
// <textarea>
//
t.onkeypress = function() {
document.getElementById("preview").innerHTML = this.value;
};

insertBefore( , )
DOM- .
, . ,
null , ,
.
. , DOM,
DOM-, .
. .28 (
URL ) URL - .
A.28. <a> -

// <a>
var a = document.getElementsByTagName("a");
for ( var i = 0; i < a.length; i++ ) {
// -,
//
var img = document.createElement("img");
img.src = a[i].href.split('/').splice(0,3).join('/') + '/favicon.ico';
//
a[i].parentNode.insertBefore( img, a[i] );
}

removeChild( )
DOM-. removeChild
, .
: DOM-, . .29
<div>- ,
warning.
A.29. ,

// <div>
var div = document.getElementsByTagName("div");
for ( var i = 0; i < div.length; i++ ) {

302
// <div> 'warning'
if ( div[i].className == "warning" ) {
// <div>
div[i].parentNode.removeChild( div[i] );
}
}

replaceChild( , )
.
.
: , DOM, ,
. .30 <a> <strong>,
URL, .
A.30. URL

// URL (
// )
// <a>
var a = document.getElementsByTagName("a");
while ( a.length ) {
// <strong>
var s = document.createElement("strong");
// , URL, <a>
s.appendChild( document.createTextNode( a[i].href ) );
// <a> <strong>
a[i].replaceChild( s, a[i] );
}

303


6, .
DOM- , 6.
, , ,
.


,
, Quirksmode.org. -
.

(http://www.quirksmode.org/js/events_compinfo.html).
: W3C DOM- Internet
Explorer HTML-. -
:

W3C DOM Level 2 events: http://www.w3.org/TR/DOM-Level-2-Events/events.html

Internet Explorer HTML events: http://msdn.microsoft.com/workshop/author/dhtml/reference/events.asp

, JavaScript,
, JavaScript,
.

,
. , - ( )
. .

/ /
( )
. ,
, .
, , .

, .
( , )
DOM .

( W3C) ,
DOM ,
.

304
( )
,
, . ,
- .

, () -. ,
(,

, ..),

(, , ).


( , ) ,
. ,
( ).

,
( , ). JavaScript -
, .


,
. Internet Explorer -.
,

W3C,

, . Internet Explorer
window.event, .


.
,
. .

type
(, click, mouseover ..).
,

6).

(,

addEvent/removeEvent,

.1

, .
.1.

type

// <div>,
var div = document.getElementsByTagName('div')[0];

305
// mouseover mouseout
div.onmouseover = div.onmouseout = function(e){
//
e = e || window.event;
// <div>,
//
this.style.background = (e.type == 'mouseover') ? '#EEE' : '#FFF';
};

target / srcElement

(click), <a> , target


<a>. srcElement target, Internet Explorer. .2
.
.2. , HTML DOM,

//
document.ondblclick = function(e) {
//
e = e || window.event;
//
var t = e.target || e.srcElement;
// DOM
t.parentNode.removeChild( t );
};

stopPropagation() / cancelBubble
stopPropagation() ( ) ,
. 6. cancelBubble
Internet Explorer; true,
stopPropagation()

W3C-

.3

.
.3. <li>,

// <li>
var li = document.getElementsByTagName('li');
for ( var i = 0; i < li.length; i++ ) {
// <li>
li[i].onmouseover = function(e){
// W3C-
if ( e )
// stopPropogation
e.stopPropagation();

306
// , Internet Explorer
else
// cancelBubble
// true
e.cancelBubble = true;
// , <li>
this.style.background = '#EEE';
};
// <li>
li[i].onmouseout = function(){
//
this.style.background = '#FFF';
};
}

preventDefault() / returnValue = false

preventDefault()

W3C- . Internet Explorer,


, returnValue, , false.
6. .4 ,
, (
), URL .
.4.

// <a>
var a = document.getElementsByTagName('a');
for ( var i = 0; i < a.length; i++ ) {
// <a>
a[i].onclick = function(e) {
// URL ,
// URL
document.title = this.href;
// -,
// <a> ( )
if ( e ) {
e.preventDefault();
// IE
} else {
window.event.returnValue = false;
}
};

307
}


, (
click, mousedown, mouseup, mouseover, mousemove mouseout).
, .
, , ,
.

clientX / clientY
x y .
.5.
.5. -

//
function getX(e) {
// -IE , IE,
//
return e.pageX || (e.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
}
//
function getY(e) {
// -IE , IE,
//
return e.pageY || (e.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));

pageX / pageY
x y (
, , ,
clientX/clientY). Internet Explorer . IE,
clientX/clientY, .

layerX / layerY offsetX / offsetY


x y .
layerX/layerY ,

Mozilla Safari,

offsetX/offsetY Opera Internet Explorer. (


.17.)

button
, , (
click, mousedown mouseup). ,

308
. .1 button Internet Explorer,
W3C- .
.1. button

Internet Explorer

W3C

.6 ,
( ) -.
.6. button

//
document.onclick = function(e) {
//
e = e || window.event;
//
if ( e.button== 2 ) {
//
e.preventDefault();
return false;
}
};

relatedTarget
,
.

mouseover/mouseout, , , .
.7 ( <ol> <ol>)
,
<li>.
.7. relatedTarget ,

// <li>,
var li = document.getElementsByTagName('li');
for ( var i = 0; i < li.length; i++ ) {
// mouseover
li[i].onmouseover = function(e){
// ( )
if ( e.relatedTarget == this.parentNode ) {
// (
// <ol>)

309
this.lastChild.style.display = 'block';
}
};
}
// HTML:
<ol>
<li>Hello <ol>
<li>Another</li>
<li>Item</li>
</ol></li>
<li>Test <ol>
<li>More</li>
<li>Items</li>
</ol></li>
</ol>


,
( keydown, keyup keypress).
ctrlKey shiftKey, , (
CtrlClick ). , ,
, .

ctrlKey
, , Ctr
, , . .8
control; , , ,
.
.8. ctrlKey ,

//
document.onclick = function(e){
//
e = e || window.event;
var t = e.target || e.srcElement;
// control ,
if ( e.ctrlKey )
// ,
t.parentNode.removeChild( t );
};

keyCode

( Page Up Home) , -

310
. . .2
.
.2.

(Backspace)

(Tab)

(Enter)

13

32

37

38

39

40

09

4857

AZ

6590

.9

<li>- <ol> <ul>.


<li> (, ).
, <li>.
.9. keyCode

// <li>
var cur = document.getElementsByTagName('li')[0];
//
cur.style.display = 'block';
//
document.onkeyup = function(e){
//
e = e || window.event;
//
if ( e.keyCode == 37 || e.keyCode == 39 ) {
// <li>-
cur.style.display = 'none';
// ,
// <li>-
// ( )
if ( e.keyCode == 37 )
cur = cur.previousSibling || cur.parentNode.lastChild;

311
// ,
// <li>-, , ,
// <li>-
else if ( e.keyCode == 39 )
cur = cur.nextSibling || cur.parentNode.firstChild;
// <li>-
cur.style.display = 'block';
}
};

shiftKey
, , Shift.
, , . .8
Shift; , .
.10. shiftKey

//
document.onclick = function(e){
//
e = e || window.event;
// Shift ,
if ( e.shiftKey )
//
document.getElementById('menu').style.display = 'block';
};

(
, ).

load
load , ;
, JavaScript, CSS.
DOM- , , ,
domReady(), 6.
.11 , ,
, ID cancel. ,
, ID main.
.11. load

//
window.onload = function(){

312
// , ID 'cancel'
//
document.getElementById('cancel').onclick = function(){
// 'main'
document.getElementById('main').style.display = 'none';
};
};

beforeunload

. unload, .
beforeunload , ,
, . ,
. -, Gmail, ,
.
.12 ( ),
, , .
, .
.12. beforeunload

// beforeunload
window.onbeforeunload = function(){
// ,
// .
return ' .';
};

error
error JavaScript.
, .
, ,
, , .
.13
.
.13. error

// error
window.onerror = function( message ){
// <li>,
var li = document.createElement('li');

313
li.innerHTML = message;
// (ID
//

'errors')

var errors = document.getElementById('errors');


//
errors.insertBefore( li, errors.firstChild );
};

resize
resize , .
, resize ,
.
.14 ,
, document (
).
.14. resize

//
window.onresize = function() {
// document
// ( )
var de = document.documentElement;
//
// ( ,
// -)
var w = window.innerWidth || (de && de.clientWidth)
|| document.body.clientWidth;
//
// document
de.className = w < 990 ? 'small' : '';
};

scroll
scroll , .
( , Page Up/Down )
.

unload
, (, ,
).
( , beforeunload).

314
.15 , unload,
, .
.15. unload

// , -
window.onunload = function(){
//
alert( ', !' );
};

(UI)
,
. ,
, (,
).

focus
focus , .
; ,
, . (
.18.)

blur
blur (
, ). (
.18.)


,
.

click
click , (.
mousedown) (. mouseup) . .16
click , .
.16. ,

// <a>
var a = document.getElementsByTagName('a');
for ( var i = 0; i < a.length; i++ ) {
// ,
//
if ( a[i].href == window.location.href ) {

315
// ''
a[i].onclick = function(e){
return false;
};
}
}

dblclick
dblclick , .
.

mousedown
mousedown , .
keydown, .
.17.

mouseup
mouseup , .
, ,
click. .17.

mousemove
mousemove ,
. mousemove ( ) ,
,
. .17 .
.17. draggable

// ,
var curDrag, origX, origY;
//
document.onmousedown = function(e){
//
e = fixEvent( e );
// , 'draggable'
if ( e.target.className == 'draggable' ) {
//
curDrag = e.target;
//
//
origX = getX( e ) + (parseInt( curDrag.style.left ) || 0);
origY = getY( e ) + (parseInt( curDrag.style.top ) || 0);

316
//
document.onmousemove = dragMove;
document.onmouseup = dragStop;
}
};
//
function dragMove(e) {
//
e = fixEvent( e );
//
if ( !curDrag || e.target == curDrag ) return;
//
curDrag.style.left = (getX(e)) + 'px';
curDrag.style.top = (getY(e)) + 'px';
}
//
function dragStop(e) {
//
e = fixEvent( e );
//
curDrag = document.mousemove = document.mouseup = null;
}
//
function fixEvent(e) {
// IE-
// W3C-
if (!e) {
e = window.event;
e.target = e.srcElement;
e.layerX = e.offsetX;
e.layerY = e.offsetY;
}
return e;
}

mouseover
mouseover ,
. , ,
relatedTarget. .18.

mouseout
mouseout , .
(

317
). , ,
relatedTarget.
.18 , -
( ).
, ,
.
.18. mouseover mouseout

// <a>-
//
var a = document.getElementsByTagName('a');
for ( var i = 0; i < a.length; i++ ) {
// <a>- mouseover
// focus, ,
// ,
// ( )
a[i].onmouseover = a[i].onfocus = function() {
this.style.backgroundColor = 'blue';
};
// <a>- mouseout
// blur, ,
//
a[i].onmouseout = a[i].onblur = function() {
this.style.backgroundColor = 'white';
};
}


, ,
.

keydown / keypress
keydown , .
, keydown . keypress

keydown,

: ,
keypress. .19 keypress,
<input>.
.19. Enter
<input>

// <input>
var input = document.getElementsByTagName('input');

318
for ( var i = 0; i < input.length; i++ ) {
// keypress <input>
input[i].onkeypress = function(e) {
// ,
return e.keyCode != 13;
};
}

keyup
keyup ( keydown).
keydown, (
).


<form>, <input>, <select>, <button>
<textarea>, HTML-.

select
select ,
, .
. .20 select
.
.20. <textarea>

// <textarea>
var textarea = document.getElementsByTagName('textarea')[0];
// select
textarea.onselect = function(){
// ,
return false;
};

change
change , ( <select>
<textarea>) . , ,
.
, .21 , ID
entryArea ( <textarea>),
.
.21. change

// 'entryArea' ( <textarea>)
document.getElementById('entryArea').onchange = function(){

319
// ,
//
document.getElementById('preview').innerHTML = this.value;
};

submit
submit ,
Submit ( ) Enter/Return .
submit , click Submit,
.
.22 , , ,
, .
.22. submit

// submit
document.getElementsByTagName('form')[0].onsubmit = function(e) {
// ,
var name = document.getElementById('name').value;
//

<h1> , ! (

// name, )
document.getElementsByTagName('h1')[0].innerHTML =
', ' + name + '!';
//
return false;
};

reset
reset Reset () (

Submit, Enter).

.23 ( reset),
.
.23.

//
var form = document.getElementsByTagName('form')[0];
// reset
form.onreset = function(){
// <input>
var input = form.getElementsByTagName('input');

320
//
for ( var i = 0; i < input.length; i++ )
input[i].value = '';
};

321


JavaScript -.
JavaScript (, )
,
. , JavaScript,
, , ( ) .


, , ,

. , ,
, ,
.
, , , JavaScript . (DOM, XMLHttpRequest
..) ,
- . ,
, , .

Internet Explorer
Microsoft ( Windows 95),
Internet Explorer -. , Microsoft
, .
, Microsoft Windows Vista (
Internet Explorer 7), .

5.5 6.0
5.5 IE, Windows 98, 6.0
Windows XP.
CSS DOM, , .

7
Internet Explorer, Windows XP
Windows Vista. , ,

Vista

.
JavaScript , ,
CSS. JavaScript , XMLHttpRequest
ActiveXObject, ( ) .

Mozilla

322
, Netscape, Mozilla
. Firefox
, Mozilla .

Firefox 1.0, Netscape 8 Mozilla 1.7


1.7 Gecko.
.
, .

Firefox 1.5 2.0


Gecko (1.8),

Firefox, ,
. SVG 1.1, <canvas>,
JavaScript 1.6. 14.

Safari
Safari Apple (
Internet Explorer 5) OS X. ( 1.0), ,
.
.
Safari (1.3 OS X 10.3, 2.0 OS X 10.4)
, . , ,
Safari, , .
<canvas>,
, -.

Opera
Opera Netscape Microsoft.
(
). Mozilla, Opera
HTML 5, .

8.5
8.5 , Opera,
, . ,
, CSS ;
JavaScript .

9.0
Opera JavaScript,
<canvas>.

Оценить