[DOM Event Learning] Section 3 jQuery事件處理基礎 on(), off()和one()方法使用


[DOM Event Learning] Section 3 jQuery事件處理基礎 on(),off()和one()方法使用

 
  jQuery提供了簡單的方法來向選擇器(對應頁面上的元素)綁定事件處理器(event handlers).
  當一個事件發生,提供的function就被執行,在方法里面,this代表當前的元素.
  這些事件通常是由於用戶和頁面的交互而被激發,比如文字輸入到表單元素,鼠標指針移動等.也有一些情況,比如頁面load和unload的事件,是由瀏覽器本身來激發.
  關於Events的細節,可以查看:http://api.jquery.com/category/events/
  事件處理方法可以接收一個event對象,這個對象被用來判定事件類型,或者制止默認行為等.
  event對象的詳細介紹可以參見:http://api.jquery.com/category/events/event-object/
 

jQuery的事件綁定方法

  jQuery為絕大多數瀏覽器事件提供了方便的方法,比如.click(), .focus(), .blur(), .change()等,它們都是.on()方法的簡便形式.
  比如下面兩個方法的效果是一樣的:
// Event setup using a convenience method
$("p").click(function () {
    console.log("You clicked a paragraph!");
});
// Equivalent event setup using the `.on()` method
$("p").on("click", function () {
    console.log("click");
});
 

.on()方法

  .on()方法使用起來很靈活,在很多場合很有用,比如為多個事件綁定同一個處理方法,當你想給處理方法傳數據,或者處理自定義事件,或當你想要傳遞多個事件和方法時.
 
  為多個事件綁定同一個處理方法時,用空格分隔事件名:
// Multiple events, same handler
$("input").on(
    "click change", // Bind handlers for multiple events
    function () {
        console.log("An input was clicked or changed!");
    }
);

 

  如果多個事件的處理方法不同,也可以一次綁定,因為.on()方法可以接收傳入一個大括號包含的PlainObject對象,其中是一個或多個key value,key是事件名,value是處理函數.
// Binding multiple events with different handlers
$("p").on({
    "click": function () {
        console.log("clicked!");
    },
    "mouseover": function () {
        console.log("hovered!");
    }
});

 

  但是需要注意的是.on()方法只能對當前存在的元素綁定事件.
  如果在.on()方法執行之后,新建了一個符合選擇器的元素,這個新建的元素並不會執行這個前面綁定的事件處理方法.
$(document).ready(function () {

    // Sets up click behavior on all button elements with the alert class
    // that exist in the DOM when the instruction was executed
    $("button.alert").on("click", function () {
        console.log("A button with the alert class was clicked!");
    });

    // Now create a new button element with the alert class. This button
    // was created after the click listeners were applied above, so it
    // will not have the same click behavior as its peers
    $("<button class='alert'>Alert!</button>").appendTo(document.body);
});

 

事件對象

  每一個事件處理函數都接收一個事件對象(Event Object),這個對象包含很多屬性和方法.
  一個很常用的方法是用.preventDefault()來阻止事件的默認行為.
  其他有用的屬性和方法包括:
  pageX, pageY: 事件發生時的鼠標指針位置.相對於頁面顯示區域的左上角,而不是瀏覽器窗口.
  type: 事件類型,比如”click”.
  which: 被點擊的button或key.
  data: 事件被綁定的時候傳入的數據.比如:
// Event setup using the `.on()` method with data
$("input").on(
    "change",
    {foo: "bar"}, // Associate data with event binding
    function (eventObject) {
        console.log("An input value has changed! ", eventObject.data.foo);
    }
);

 

  target: 初始化這個事件的DOM元素,也即分發這個事件的元素.
  namespace: 這個事件激發時指定的namespace.
  timeStamp: 事件發生時距離1970年1月1日的時間戳,單位是milliseconds.
 
  preventDefault(): 阻止事件的默認行為.
  stopPropagation(): 阻止事件向上冒泡到其他元素.
  這兩個方法一起用的時候,可以用return false來代替,更加簡潔.
 
  originalEvent屬性是瀏覽器自己創造的一個event對象,jQuery又包裝了一下這個對象,有一些有用的方法和屬性,這些在處理移動設備的touch events的時候很有用.
 
  除了事件對象之外,事件處理函數還可以通過this關鍵字訪問該事件綁定的DOM元素,我們可以把這個DOM元素轉換為jQuery對象:
var $element = $(this);

 

解除事件監聽器

  要解除event listener,可以使用.off()方法,傳入要解除綁定的事件類型.
  如果你附加了一個有名字的function,那么你可以通過第二個參數,指定僅解除這個名字的事件處理函數.
// Tearing down all click handlers on a selection
$("p").off("click");

// Tearing down a particular click handler, using a reference to the function
var foo = function () {
    console.log("foo");
};
var bar = function () {
    console.log("bar");
};

$("p").on("click", foo).on("click", bar);
$("p").off("click", bar); // foo is still bound to the click event
 
 

設置只執行一次的事件處理

  有時候你需要一個handler只執行一次,或者你想執行一次之后換一個handler, jQuery為這種情況提供了.one()方法.
// Switching handlers using the `.one()` method
$("p").one("click", firstClick);

function firstClick() {
    console.log("You just clicked this for the first time!");

    // Now set up the new handler for subsequent clicks;
    // omit this step if no further click responses are needed
    $(this).click(function () {
        console.log("You have clicked this before!");
    });
}
  注意上面這段代碼中,這個firstClick方法將在所有p元素第一次被點擊的時候執行一次,而不是某個p被點擊一次之后就從所有p中移除該方法.
 
  .one()方法也可以用來綁定多個事件:
// Using .one() to bind several events
$("input[id]").one("focus mouseover keydown", firstEvent);

function firstEvent(eventObject) {
    console.log("A " + eventObject.type + " event occurred for the first time on the input with id " + this.id);
}
   這種情況下,所有事件的第一次執行都會進入這個處理方法.
  對這段代碼來說,也即,即便input已經獲得了焦點,但是第一次keydown事件的時候還是會執行這個方法.
 
 

參考資料

  jQuery Events: http://learn.jquery.com/events/
  jQuery API Events: http://api.jquery.com/category/events/
 
  w3school jQuery參考手冊 事件: http://www.w3school.com.cn/jquery/jquery_ref_events.asp
  JavaScript事件參考手冊: http://www.w3school.com.cn/jsref/jsref_events.asp
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM