<ul>
<li>111111111</li>
<li>222222222</li>
<li>33333333333</li>
<li>444444444444444</li>
</ul>
<li>55555555555</li>
<br>
<button id="btn">添加新的li</button>
<br>
新增加的元素没有监听
$('ul>li').click(function(){
this.style.background='red'
})
$('#btn').click(function(){
$('<li>vvv</li>').appendTo('ul')
})
解决办法:事件委托
将多个子元素li的事件监听委托给父辈元素ul处理
监听回调函数是加在父辈元素上
当操作任何一个子元素li时,事件会冒泡到父辈元素ul
父辈元素不会直接处理事件,而是根据event.target得到发生事件的子元素li(知道事件发生的对象)。通过这个子元素调用事件回调函数
委托方:业主li 被委托方:中介ul
使用事件委托的好处:添加新的子元素,自动事件响应处理
减少事件监听的数量:n===》1
使用的函数有:父元素.delegate(子元素 事件名 回调函数) this是发生事件的子元素
console.log(event.target===this);//ture
$('#btn').click(function(){
$('<li>vvv</li>').appendTo('ul')
})
$('ul').delegate('li','click',function(event){
//this是点击的dom元素
this.style.background='red'
})
移除事件的委托:父元素.undelegate(事件)
不传递 是所有事件
$('#btn').click(function() {
$('<li>vvv</li>').appendTo('ul')
})
$('ul').delegate('li', 'click', function(event) {
//this是点击的dom元素
console.log(event.target === this); //ture
this.style.background = 'red'
})
$('#btn2').click(function() {
$('ul').undelegate('click');
})