<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .active{ color: red; } </style> </head> <body> <button class="btn">按钮</button> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <script> // EventTarget移除 var btnEle=document.querySelector('.btn'); function fn(){ console.log('输出'); } btnEle.addEventListener('click',fn) var time1=setInterval(function(){ btnEle.removeEventListener('click',fn) },5000) // 事件派发 window.addEventListener('yt',function(){ console.log('来自yt的呼唤'); }) // 派发'yt'事件 window.dispatchEvent(new Event('yt')); //事件委托event delegation //ul下面4个li,点击li对应的li变红色 var ulEle=document.querySelector('ul'); var activeLiel=null;//第一次先置空 ulEle.addEventListener('click',function(e){ //方法一 //将已经拥有active的移除 // var actEle=ulEle.querySelector('.active'); // actEle&&actEle.classList.remove('active');//在actEle有值的情况下调用后面 // 方法二,用变量记录e.target activeLiel&&activeLiel.classList.remove('active')//在activeLiel有值的情况下调用后面 //给点击的对象添加类属性 e.target.classList.add('active'); // 给activeLiel赋值 activeLiel=e.target; }) </script> </body> </html>
标签:function,派发,activeLiel,JavaScript,var,actEle,移除,active From: https://www.cnblogs.com/theYT/p/16871371.html