JQuery事件綁定,移除綁定

下面主要講解JQuery事件綁定的三種方式: 

             【1】 bind()

             【2】 delegate()

             【3】 on()

【1】bind() 綁定    隱式迭代:爲選擇器選擇的所有元素全部綁定相同事件    this是document類型,使用時要用 $(this)

           $(selector).bind(event,fun);    

                  【1.1】=> $("div p").bind("click",function(){    //要執行的代碼   alert($(this).text());   })   //匿名函數綁定

                     【1.2】=> $("div p").bind("click",funName(parm)); //綁定函數

                【1.3】=> $("div p").click(function(){  //要執行的代碼   alert($(this).text());  });  

【2】delegate()綁定   運用的事件委託的概念和事件冒泡 爲父元素綁定事件,當觸發子元素事件時,事件冒泡觸發父元素的相應事件

         $(selector).delegate("selector-c",event,fun);    //  selector-cselector的子元素

                 【2.1】=>$("div").delegate("p","click",function(){   //要執行的代碼   alert($(this).text());   });

【3】on()綁定  無論是bind() 還是 delegate 本質上都是採用了on()綁定事件 只是傳遞的參數不同

          $(selector).on(event,"selector-c",fun);

          $(selector).on(event,fun)          

【4】移除綁定的方法  

             $(seletor).unbind(event,handler) 

             $(seletor).undelegate(selectot-c,event,handler) 

            $.(seletor).off(event,selector,handler)

總結

1.選擇器匹配到的元素比較多時,不要用bind()隱式迭代綁定

2.用id選擇器時,可以用bind()

3.需要給動態添加的元素綁定時,用delegate()或者on()

4.用delegate()和on()方法,document 樹不要太深

5.儘量使用on()

        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章