事件代理:子元素的监听事件委托给父容器处理,事件的监听回调加在父容器上面,但是event.target却指向子元素
事件代理应用场景:当子元素众多,或者会动态增加时,可以一次性给所有子元素,包括新增子元素,都添加事件
//添加事件代理 $(’#parent’).delegate(’.child’,‘click’,function(){ this.style.background = ‘red’ })
//移除事件代理 $(’#parent’).undelegate() $(’#parent’).undelegate(‘click’) $(’#parent’).undelegate(’.child’,‘click’)
注意:添加和移除时的选择器必须完全一致,删除并不是按照匹配的元素来依次删除事件的