12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <!--
- 事件委托:
- 减少内存消耗 避免多次循环
- -->
- <ul id="list">
- <li>1</li>
- <li>2</li>
- <li>3</li>
- <li>4</li>
- </ul>
- <button class="btn">添加</button>
- <script>
- var list = document.getElementById("list");
- var lists = document.querySelectorAll("#list li");
- var btn = document.getElementsByClassName("btn")[0];
- // console.log(btn)
- btn.onclick = function() {
- var li1 = document.createElement("li");
- console.log(li1)
- li1.innerText = Math.round(Math.random()*9+1);
- list.appendChild(li1);
- }
- list.onclick = function(event) {
- console.log(event)
- if(event.target.nodeName == 'LI') {
- console.log(event.target.innerText)
- }
- }
- // lists.onclick = function(event) {
- // console.log(event,'121')
- // }
- // console.log(lists)
- </script>
- </body>
- </html>
|