HTML DOM 事件:监听、传播与生命周期
理解事件属性、监听器、字段变化和鼠标事件的适用条件。
学完这一章,你能够
- 理解事件属性、监听器、字段变化和鼠标事件的适用条件。
- 解释对应代码的输入、动作、返回与限制
- 通过本章独立实例观察实际DOM变化
从事件属性到监听器
onclick可以写在HTML属性中,也可以在JavaScript中赋为函数;不要把调用函数的返回值误赋给onclick。addEventListener支持多个监听器,并通过同一个函数引用移除。
监听器中的event.target是事件目标,currentTarget是当前正在执行监听器的对象。普通函数的this与箭头函数的词法this不同,显式使用事件对象更清晰。
加载、退出与字段变化
DOMContentLoaded通常表示文档解析完成,load还涉及资源加载。旧的onload/onunload和Cookie能力检测知识应保留,但unload并不可靠,不应用它保证保存操作。
可根据场景使用visibilitychange或pagehide;这些替代也不是网络请求必定送达的保证。Cookie是否可用须在真实独立HTTP环境检查,沙箱能力不能靠模拟文字替代。
input通常反映编辑过程,change反映提交修改的时机,具体行为取决于控件。大写转换示例应考虑光标和输入法组合状态,简单练习不等于生产级输入组件。
鼠标、键盘与传播
mouseover/out可能因进入子节点而触发,mouseenter/leave的传播行为不同。常见鼠标点击包含down、up及click,但拖动、取消、键盘激活等场景不应机械套同一顺序。
事件委托可以利用冒泡统一处理新增后代。preventDefault影响可取消的默认行为,stopPropagation影响传播;二者不能互相代替。
完整源码与实际运行
"use strict";
const results=Object.create(null);
const emit=(key,value)=>{results[key]=value===undefined?{type:"undefined"}:value;document.querySelector("#output").textContent=JSON.stringify(results,null,2);};
window.__mbskyResults=results;window.__mbskyErrors=[];
window.addEventListener("error",e=>window.__mbskyErrors.push(e.message));
(async()=>{
const button=document.querySelector('#event-button');const field=document.querySelector('#name');let count=0;
function increment(event){count++;emit('clickCount',count);emit('target',event.target.id);emit('currentTarget',event.currentTarget.id);}
button.addEventListener('click',increment);document.querySelector('#parent').addEventListener('click',()=>emit('bubbled',true));
field.addEventListener('input',()=>emit('input',field.value));field.addEventListener('change',()=>{field.value=field.value.toUpperCase();emit('change',field.value);});
button.addEventListener('mousedown',event=>emit('down',event.button));button.addEventListener('mouseup',event=>emit('up',event.button));
button.addEventListener('mouseover',()=>emit('over',true));button.addEventListener('mouseout',()=>emit('out',true));
window.addEventListener('load',()=>emit('loaded',true));document.addEventListener('visibilitychange',()=>emit('visibility',document.visibilityState));
window.removeDemoListener=()=>button.removeEventListener('click',increment);
})().then(()=>window.__mbskyDone=true).catch(error=>{window.__mbskyErrors.push(String(error));emit("runtimeError",String(error));window.__mbskyDone=true;});
所需环境:现代浏览器与本站独立HTTP实验服务
当前源码 SHA256:b809441c528dfc8817303a29db7e74d4515b0c509235b999070622129b521c94
- {"click": {"clickCount": 1, "target": "event-button", "currentTarget": "event-button", "bubbled": true}}
常见错误与边界
- 没有检查null就直接访问节点属性。
- 把源码存在、属性赋值或示例可打开当成实际教学行为已验收。
- 在file或不具备能力的沙箱内推断HTTP、Cookie和同源行为。
练习与解答
修改本章实例的一项输入,记录操作前后输出;再构造一个正文提到的失败或边界条件。
展开参考解答
先保存操作前的DOM或属性值,再执行单一操作并比较输出。查询不到、非法参照、实时集合变化及资源加载失败按对应章节处理,不伪造成功结果。