1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <!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>添加</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>
|