上一篇:内存专题 下一篇:数组专题

事件优化

事件优化

  • 使用事件代理

    • 当存在多个元素需要注册事件时,在每个元素上绑定事件本身就会对性能有一定损耗。
    • 由于DOM Level2事件模 型中所有事件默认会传播到上层文档对象,可以借助这个机制在上层元素注册一个统一事件对不同子元素进行相应处理。

    捕获型事件先发生。两种事件流会触发DOM中的所有对象,从document对象开始,也在document对象结束。

    • Item 1
    • Item 2
    • Item 3
    • Item 4
    • Item 5
    • Item 6
    // 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!"); } });
上一篇:内存专题 下一篇:数组专题