e 1 yıl önce
ebeveyn
işleme
59fc48076d

+ 40 - 0
JS初级/DOM/23.事件委托.html

@@ -0,0 +1,40 @@
+<!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>
+    <div id="btn">添加</div>
+    <!-- 事件委托: 减少内存消耗 避免多次循环 -->
+    <script>
+        var list = document.querySelectorAll("#list li")
+        var lis = document.getElementById("list");
+        var btn = document.getElementById("btn")
+        // console.log(list)
+        // for(var i=0;i<list.length;i++) {
+        //     console.log(list[i]);
+        //     list[i].onclick = function() {
+        //     }
+        // }
+        lis.onclick = function(event) {
+            // console.log(event);
+            if(event.target.nodeName == 'LI') {
+                console.log(event.target.innerHTML);
+            }
+        }
+        btn.onclick = function() {
+            var li1 = document.createElement("li");
+            li1.innerHTML = Math.round(Math.random() * 9 + 1);
+            lis.appendChild(li1);
+        }
+    </script>
+</body>
+</html>

+ 45 - 0
JS初级/DOM/24.this指向问题.html

@@ -0,0 +1,45 @@
+<!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>
+        #box {
+            width: 200px;
+            height: 200px;
+            background: #f00;
+        }
+    </style>
+</head>
+<body>
+    <div id="box"></div>
+    <script>
+        var box = document.getElementById("box");
+        //1. 点击事件 this指向点击的对象
+        box.onclick = function() {
+            console.log(this); //box
+        }
+        // 2.倒计时 this指向window
+        box.onclick = function() {
+            setInterval(function() {
+                console.log(this); // 
+            },1000)
+        }
+        // 3.对象中的this 指向当前对象
+        var obj = {
+            name:"Lucy",
+            age: 18,
+            address:function() {
+                console.log(this);
+            }
+        }
+        obj.address()
+        //4.函数中的this 指向window
+        function fn1() {
+            console.log(this);
+        }
+        fn1();
+    </script>
+</body>
+</html>