自 jQuery 1.7 起,on() 成為官方推薦的事件綁定方式。這篇把它的參數、優勢,以及與 bind/live/delegate 的關係一次講完。
on(events [, selector] [, data], fn)
它提供了一套統一的事件綁定接口,同時保留了 delegate() 的優勢——可以用事件 delegation 處理動態加入的元素;如果你確實想直接綁在元素上,也可以照舊寫。
其實這三個方法在原始碼裡都是呼叫 on() 實作的:
bind: function (types, data, fn) {
return this.on(types, null, data, fn);
},
unbind: function (types, fn) {
return this.off(types, null, fn);
},
live: function (types, data, fn) {
jQuery(this.context).on(types, this.selector, data, fn);
return this;
},
die: function (types, fn) {
jQuery(this.context).off(types, this.selector || "**", fn);
return this;
},
delegate: function (selector, types, data, fn) {
return this.on(types, selector, data, fn);
},
undelegate: function (selector, types, fn) {
return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
}
幾個重點:
1. 綁定 click,並用 off() 解除
$(document).ready(function () {
$("p").on("click", function () {
$(this).css("background-color", "pink");
});
$("button").click(function () {
$("p").off("click");
});
});
2. 多個事件共用同一個函式
$(document).ready(function () {
$("p").on("mouseover mouseout", function () {
$("p").toggleClass("intro");
});
});
3. 多個事件各綁不同函式
$(document).ready(function () {
$("p").on({
mouseover: function () { $("body").css("background-color", "lightgray"); },
mouseout: function () { $("body").css("background-color", "lightblue"); },
click: function () { $("body").css("background-color", "yellow"); }
});
});
4. 綁定自訂事件
$(document).ready(function () {
$("p").on("myOwnEvent", function (event, showName) {
$(this).text(showName + "! What a beautiful name!").show();
});
$("button").click(function () {
$("p").trigger("myOwnEvent", ["Anja"]);
});
});
5. 傳入資料給處理函式
function handlerName(event) {
alert(event.data.msg);
}
$(document).ready(function () {
$("p").on("click", { msg: "You just clicked me!" }, handlerName);
});
6. 處理尚未建立的元素(事件 delegation)
$(document).ready(function () {
$("div").on("click", "p", function () {
$(this).slideToggle();
});
$("button").click(function () {
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
最後這段最能體現 on() 的價值:即使 p 是在綁定之後才動態插入的,點擊依然有效果。
希望這篇對大家的 jQuery 開發有幫助。