Javascript 第三章
1 <html>
2 <head>
3 <title></title>
4
5 </head>
6 <body>
7 <form action="test_submit" method="get" accept-charset="utf-8" class="test" id="form1">
8
9 <div class="test"></div>
10 <div class="test"></div>
11
12 </form>
13 <p title="p1">One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought.</p>
14 <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought.</p>
15 <p title="p3">One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought.</p>
16
17 <script>
18 // implement getElementsByClassName
19 function getElementsByClassName(note,classname){
20 // if(!note) equivalent to if (note == null) {};
21 var args = arguments.length;
22 if (args == 1) {
23 classname = arguments[0];
24 note = document;
25 }else if (args == 2) {
26 classname = arguments[1];
27 if (!note) {
28 note = document;
29 }else{
30 note = arguments[0];
31 }
32 }
33
34 classname = classname.toString();
35 if(note.getElementsByClassName){
36 return note.getElementsByClassName(classname);
37 }else{
38 var results = [];
39 var elements = note.getElementsByTagName("*");
40 for (var i = 0,j = elements.length; i < j; i++) {
41 if (elements[i].className.indexof(classname) != -1) {
42 results[results.length] = elements[i];
43 }
44 }
45
46 return results;
47 }
48 }
49
50
51 alert(getElementsByClassName("test").length);
52
53
54 var paras = document.getElementsByTagName("p");
55 for (var i = 0; i < paras.length; i++) {
56 var title_text = paras[i].getAttribute("title");
57 if (title_text) {
58 alert(title_text);
59 }else{
60 paras[i].setAttribute("alt","alt"+(i+1));
61 alert(paras[i].getAttribute("alt"));
62 }
63 }
64 </script>
65 </body>
66 </html>