企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 事件优化 > * 使用事件代理 > > > * 当存在多个元素需要注册事件时,在每个元素上绑定事件本身就会对性能有一定损耗。 > * 由于DOM Level2事件模 型中所有事件默认会传播到上层文档对象,可以借助这个机制在上层元素注册一个统一事件对不同子元素进行相应处理。 > > 捕获型事件先发生。两种事件流会触发DOM中的所有对象,从document对象开始,也在document对象结束。 > > > > ~~~ > <ul id="parent-list"> > <li id="post-1">Item 1 > <li id="post-2">Item 2 > <li id="post-3">Item 3 > <li id="post-4">Item 4 > <li id="post-5">Item 5 > <li id="post-6">Item 6 > </li></ul> > // Get the element, add a click listener... > document.getElementById("parent-list").addEventListener("click",function(e) { > // e.target is the clicked element! > // If it was a list item > if(e.target && e.target.nodeName == "LI") { > // List item found! Output the ID! > console.log("List item ",e.target.id.replace("post-")," was clicked!"); > } > }); > ~~~