转:jquery给动态dom绑定事件
如果需要给一个按钮绑定事件,在jquery中一般是这样实现的。
1 $("#id").click(function(){ 2 console.log("hello world!"); 3 });
但是在给动态生成的dom绑定事件的时候,无法绑定了。查询了jquery API,如果需要给还不存在的节点绑定事件,可以通过on方法解决这个问题,即事件委托。
在jQuery 中,通过事件冒泡的特性,让子元素绑定的事件冒泡到父元素或祖先元素上,然后再进行相关处理即可,如果是后来动态生成的子元素,可以自动给其绑定事件。
1 $("#parentId").on('click','.children',function(){ 2 console.log("hello world!"); 3 });
与此同时,取消绑定可以使用off()方法。
on()方法在1.7版本后推出,除了on()方法,还有 live() bind() delegate() 实现类似的功能,live()方法是在1.9版本以后已经废弃,bind(),delegate()和on()有什么区别,大概看了下源码。
1 jQuery.fn.extend( { 2 3 bind: function( types, data, fn ) { 4 return this.on( types, null, data, fn ); 5 }, 6 unbind: function( types, fn ) { 7 return this.off( types, null, fn ); 8 }, 9 10 delegate: function( selector, types, data, fn ) { 11 return this.on( types, selector, data, fn ); 12 }, 13 undelegate: function( selector, types, fn ) { 14 15 // ( namespace ) or ( selector, types [, fn] ) 16 return arguments.length === 1 ? 17 this.off( selector, "**" ) : 18 this.off( types, selector || "**", fn ); 19 }, 20 size: function() { 21 return this.length; 22 } 23 } );
bind(),delegate()的底层实现都是调用on()方法,至于on()方法,源码中通过event.add方法实现。
1 jQuery.event.add( this, types, fn, data, selector );
继续啃~
文章转自:https://blog.csdn.net/zhaozjc112/article/details/51849799
                    
                
                
            
        
浙公网安备 33010602011771号