[英]Can't trigger self-made Event.prototype
我有這個原型功能 - >
Event.prototype.eventPreventDefault = function () {
this.preventDefault ? this.preventDefault() : this.returnValue = false;
}
我通過這樣做來調用代碼 - >
$element.click(function (evt) {
evt.eventPreventDefault();
}
但我明白了
未捕獲的TypeError:undefined不是函數
我做錯了什么? 謝謝!
由jQuery創建的事件對象(並傳遞給事件處理程序)不是本機事件的子項( “首選組合而不是繼承”原則 )。 他們有自己的一組方法 (在jQuery.Event.prototype
上jQuery.Event.prototype
):
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
// ... and so on.
};
如您所見,這些方法通常調用原始Event的同名方法(存儲在jQuery.Event實例的originalEvent
屬性中)。 關鍵是, jQuery.Event
在其繼承鏈中沒有Event.prototype
,因此對后者的任何修改都注定對前者沒有影響。
底線:擴展傳遞給jQuery事件處理程序的事件,擴展jQuery.Event.prototype
而不是Event.prototype
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.