1 <body>
2 <button>按钮1</button>
3 <button>按钮2</button>
4 <button>按钮3</button>
5 <button>按钮4</button>
6 <button>按钮5</button>
7 <button>按钮6</button>
8
9 <script>
10 window.onload = function (ev) {
11 var buttons = document.getElementsByTagName('button');
12 for (var i = 0; i < buttons.length; i++) {
13 console.log(i + '<br>');
14 (function (i) {
15 buttons[i].onclick = function (ev1) {
16 alert('点击了第' + i + '个按钮!');
17 }
18 })(i)
19 }
20 }
21 </script>
22 </body>
1 <body>
2 <div id="box">
3 <div class="box-top">
4 <label>
5 发表评论:
6 <textarea id="my_textarea" cols="60" rows="10"></textarea>
7 </label>
8 <button id="btn">发表</button>
9 </div>
10 <ul id="ul"></ul>
11 </div>
12 <script>
13 window.addEventListener('load', function (ev) {
14 $('btn').addEventListener('click', function (ev1) {
15 var my_textarea = $('my_textarea');
16 // 1. 获取输入框中的内容
17 var content = my_textarea.value;
18 // 2. 判断
19 if(content.length === 0){
20 alert('请输入评论的内容~');
21 return;
22 }
23
24 // 3. 创建li标签放入ul
25 var ul = $('ul');
26 var li = document.createElement('li');
27 li.innerHTML = content + '<a href="javascript:;">删除</a>';
28 ul.insertBefore(li, ul.children[0]);
29
30 // 4. 清除输入框中的内容
31 my_textarea.value = '';
32
33
34 // 5. 删除评论
35 var as = ul.getElementsByTagName('a');
36 for (var i = 0; i < as.length; i++) {
37 var a = as[i];
38 a.addEventListener('click', function (evt) {
39 this.parentNode.remove();
40 });
41 }
42 });
43
44
45 function $(id) {
46 return typeof id === 'string' ? document.getElementById(id) : null;
47 }
48 });
49 </script>
50 </body>
![]()