jQuery綁定事件處理器

事件綁定相對於交互頁面是一個非常重要的一個技術,jQuery在事件綁定上面也做了很多。

目錄

bind()

delegate()

on()

off()

one()

unbind()

undelegate()


bind()

描述:爲一個元素綁定一個事件,有三個參數,第一個爲事件類型,第二個爲處理函數,第三個是布爾值,當爲false的時候,阻止冒泡,爲true爲冒泡事件。

$(function {
    $('.box').bind('click',function(){
        console.log(123);
    })
})

同時bind()也可以綁定多個事件

$(function{
     $('.box').bind("click mouseenter",function(){
          console.log(123);
     })
})

綁定多個事件顯示不同內容,一對象的形式編寫

$(function(){
    $('.box').bind({
        click : function(){
            console.log(1);
        },
        mouseover : function(){
           console.log(2);
        }
    })
})

delegate()

描述:事件委託。

3個參數 1 選擇器 2時間類型 3處理函數

$(function() {
     $('ul').delegate('li','click',function(){
          console.log($(this).html());
     })
})

on()

描述:爲一個元素添加一個事件處理器,這個是最重要的,也是最常用的。

$(function (){
     $('#btn').on('click',function(){
           console.log(1);
     })
})

它也可以寫成事件委託

三個參數 1事件類型 2 事件源 3 執行函數

$('ul').on('click','li',function(){
        console.log($(this).html());
})

同樣也可以綁定多個事件。

$(function (){
     $('p').on('mouseenter mouseleave' , function(){
            console.log(123);
     })
})

也可以綁定多個事件處理函數,以對象的形式

$(function(){
      $('p').on({
          click : function(){
               console.log(123);
          },
          mouseenter : function(){
               console.log(456);
          },
      })
})

off()

描述:移除事件,只能移除on事件綁定器綁定的時間

var handle = function(){
        console.log(123);
}
$(function(){
    $('div').on("click mouseover",'p',handle);
    //移除mouseover事件
    $('div').off('mouseover' , 'p' ,  handle );
    //當off方法的參數都不寫的時候。是移除所有事件
    $('div').off();
});

one()

描述:爲元素綁定事件,綁定的事件只能執行一次。

$(function(){
     $('p').one('click', function(){
          console.log(1);
     })
})

unbind()

描述:bind()事件的移除事件

 $(function(){
     var handle = function(){
          console.log(1);
     }
     $('p').bind('click',handle);
     $('p').unbind('click' , handle);
})

undelegate()

描述:移除undelegete事件

$(function(){
      var handle = function(){
         console.log($(this).html());
       }
       $('div').delegate('p','click',handle);
        $('div').undelegate('p' , 'click' , handle);
})

主頁傳送門

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