批改状态:合格
老师批语:
1.拿到元素(主体)
2.给主体添加事件
3.给主体添加事件监听(可以添加多个事件
)
4.事件删除
5.事件派发(先自定义事件,然后用dispatchEvent将自定义事件派发到主体)
6.定时器:setInterval
<!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>事件添加与删除</title></head><body><!--* 事件三要素:* 1.名称:字符串,'click','keydown','scroll'* 2.主体 :元素,'<button>','<div>','<form>'* 3.方法:函数,''function(ev){},()=>{}'--><div><button>1.事件属性</button><button>2.事件监听</button><button>3.事件派发</button></div><script>const div = document.querySelector('div');// (一)事件属性const btn1 = div.firstElementChild;// 1. 事件添加btn1.onclick = function () {//this:事件主休(绑定)//this -> <button>console.log(this);};//箭头函数btn1.onclick = () => {// 箭头函数没有this// 它的this是执行上下文/环境/父级console.log(this);console.log(event.target);};// 2.事件删除btn1.onclick = null;// (二) 事件监听// 1,事件添加const btn2 = btn1.nextElementSibling;const fn1 = function () {console.log(this);};const fn2 = function () {console.log('这是第二个事件');};// btn2.addEventListener(事件名称,事件方法,事件方式)// false:表示事件在冒泡阶段触发,False是默认值btn2.addEventListener('click', fn1, false);btn2.addEventListener('click', fn2, false);// 在元素上面直接写 onclick只能添加一个事件,事件监听器可以写多个//----------------------------------------------// 2.事件删除//移除第二个事件btn2.removeEventListener('click', fn1, false);//匿名事件btn2.addEventListener('click',function () {console.log('hello');},false);// btn2.removeEventListener(// 'click',// function () {// console.log('hello');// },// false// );//匿名事件不能移除//----------------------------------------------// 3. 事件派发// 将自定义事件,指定到特定的元素上触发const btn3 = div.lastElementChild;let acc = 0;btn3.onclick = function () {acc += 5;console.log(`当前余额:${acc} 元`);};//事件自动派发,就要自定义事件,自动派发到这个按钮上//1.创建一个自定义事件const adsclick = new Event('click');//2. 将自定义的属性派发到按钮上//现在模拟用户点击(事件派发)// btn3.dispatchEvent(adsclick);// btn3.dispatchEvent(adsclick);// btn3.dispatchEvent(adsclick);// btn3.dispatchEvent(adsclick);//定时器//1.一次性(只执行一次)// set Timeout(callback,time)setTimeout(() => {btn3.dispatchEvent(adsclick);}, 2000);//2.间歇式(重复不断执行)let timer = setInterval(() => {btn3.dispatchEvent(adsclick);//设定一个if(acc>=100){clearInterval(timer)console.log('今天已经赚了:',acc,'元')}}, 1000);</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号