About delegate event delegates how to use

 



Add a click event to each li, CPC must loop through it again, if there are a lot of li will affect performance.

Let's look at how to achieve a normal function click event
< div class =" box " >
< ul >
< li ></ li >
< li ></ li >
< li ></ li >
< li ></ li >
< li ></ li >
< li ></ li >
</ ul >
</ div >
< The INPUT class = ' btn ' of the type = " the Button " value = " Click to add " >
// ordinary click event
$(function(){
$("li").click(function(){
$(this).css('background','red')
});
});
// delegate event delegation:
$(function(){
$('ul').delegate("li",'click',function(ev){
$(this).css('background','red')
//这里的this 只的是li,那怎么找到ul呢?
$(ev.delegateTarget).css('background','green')//这个可以找到委托人ul
//那取消委托呢?
$($(ev.delegateTarget)).undelegate("click")
});
})
// delegate 事件委托:事件委托的有点1.提高性能 2.后面追加的元素也带有相同的事件
$(function(){
$('ul').delegate("li",'click',function(ev){
$(this).css('background','red')
//这里的this 只的是li,那怎么找到ul呢?
$(ev.delegateTarget).css('background','green')//这个可以找到委托人ul
//那取消委托呢?
$($(ev.delegateTarget)).undelegate("click")
});
$(".btn").on("click",function(){
$(".box ul").append(" < li >追加进来的 </ li >")
console.log($(".box ul"))
})
})

Guess you like

Origin www.cnblogs.com/hilxj/p/11113847.html