fengchuanyu 1 месяц назад
Родитель
Сommit
d36e35833d

+ 14 - 9
4-BOM&DOM/16_DOM事件机制.html

@@ -36,18 +36,23 @@
         // }
 
         oBox1.addEventListener("click",function(){
-            console.log("3-box1")
+            console.log("4-box1")
         },false)
-        oBox2.addEventListener("click",function(){
-            console.log("4-box2")
+        oBox2.addEventListener("click",function(e){
+            console.log("3-box2")
+            // 阻止事件冒泡
+            e.stopPropagation();
         },false)
 
-        oBox1.addEventListener("click",function(){
-            console.log("1-box1")
-        },true)
-        oBox2.addEventListener("click",function(){
-            console.log("2-box2")
-        },true)
+        // 事件捕获
+        // 事件捕获:事件从文档的根元素(html标签)开始,然后逐步向下捕获到触发事件的元素,直到到达目标元素。
+        // 事件捕获的过程中,事件处理函数会按照元素的层级关系,从外到内依次执行。
+        // oBox1.addEventListener("click",function(){
+        //     console.log("1-box1")
+        // },true)
+        // oBox2.addEventListener("click",function(){
+        //     console.log("2-box2")
+        // },true)
     </script>
 </body>
 </html>

+ 30 - 0
4-BOM&DOM/19_DOM事件委托.html

@@ -0,0 +1,30 @@
+<!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>
+    <div id="box">
+        <span>a</span>
+        <span>b</span>
+        <span>c</span>
+    </div>
+    <script>
+        // var aSpan = document.getElementsByTagName("span");
+        // for(var i=0;i<aSpan.length;i++){
+        //     aSpan[i].onclick = function(){
+        //         console.log(this.innerText);
+        //     }
+        // }
+
+        var oBox = document.getElementById("box");
+        oBox.onclick = function(e){
+            // console.log(this.innerText)
+            console.log(e.target.innerText)
+
+        }
+    </script>
+</body>
+</html>

+ 31 - 0
4-BOM&DOM/练习10_DOM动态添加数据.html

@@ -0,0 +1,31 @@
+<!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>
+    </ul>
+    <button id="btn">添加</button>
+    <script>
+        var oBtn = document.getElementById("btn");
+        var oList = document.getElementById("list");
+        var num = 3;
+
+        oBtn.onclick = function(){
+            // 创建元素
+            var oLi = document.createElement("li");
+            num++;
+            oLi.innerText = num;
+            // 将元素插入到页面中
+            oList.append(oLi);
+            // oList.appendChild(oLi);
+        }
+    </script>
+</body>
+</html>