zheng 1 week ago
parent
commit
3f5ce2c9c4
1 changed files with 84 additions and 0 deletions
  1. 84 0
      11.复习/1.事件委托.html

+ 84 - 0
11.复习/1.事件委托.html

@@ -0,0 +1,84 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        #box1 {
+            width: 400px;
+            height: 400px;
+            background: #00f;
+        }
+
+        #box2 {
+            width: 200px;
+            height: 200px;
+            background: #ff0;
+        }
+    </style>
+</head>
+
+<body>
+    <ul>
+        <li>1</li>
+        <li>2</li>
+        <li>3</li>
+        <li>4</li>
+    </ul>
+    <button @click="handleAdd">添加</button>
+    <div id="box1">
+        <div id="box2"></div>
+    </div>
+    <script>
+        // 五种
+        // document.getElementById id名称的元素 <li>1<li>
+        // document.querySelector("li") <li>1<li>
+        // document.getElementsByClassName()[0] []
+        // document.querySelectorAll() []
+        // document.getElementsByTagName() []
+        let btn = document.querySelector("button");
+        let uls = document.querySelector("ul");
+        let lis = document.querySelectorAll("li");
+        console.log(lis,'lis')
+        uls.onclick = function (event) {
+            // console.log("111",event)
+            // 减少内存消耗 避免多次循环
+            if(event.target.nodeName == "LI") {
+                console.log(event.target.innerText)
+            }
+        }
+
+        // lis.forEach((item) => {
+        //     item.onclick = function() {
+        //         console.log(item.innerText)
+        //     }
+        // })
+        // btn.onclick = function () { }
+        btn.addEventListener('click', function () {
+            // 创建标签
+            var li1 = document.createElement("li");
+            // 设置标签内容
+            // Math.random() 生成随机数
+            // 固定数值随机生成 
+            // Math.random()*(y-x)+x
+            li1.innerText = Math.round(Math.random() * 9 + 1)
+            uls.appendChild(li1);
+        })
+        var box1 = document.getElementById("box1");
+        var box2 = document.getElementById("box2");
+        // 默认事件冒泡阶段 false
+        box1.addEventListener("click", function () {
+            console.log("box111")
+        }, false)
+        //  removeEventListener 移除事件
+        // 事件捕获阶段 true
+        box2.addEventListener("click", function () {
+            console.log("box222")
+        }, false)
+        // 事件:事件捕获 目标阶段 事件冒泡
+    </script>
+</body>
+
+</html>