我是 jQuery 中的 OOP 新手。
我有以下类(class)
/*
* myClass
*/
var AlcoholOrder = function (options) {
/*
* Variables accessible
* in the class
*/
var vars = {
myVar: 'original Value'
};
/*
* Can access this.method
* inside other methods using
* root.method()
*/
var root = this;
/*
* Constructor
*/
this.construct = function (options) {
$.extend(vars, options);
};
var addRemoveFavorite = function(){
alert('function called');
};
$(function () {
$(document.body).on('click', '.favorite-add', this.addRemoveFavorite);
});
/*
* Pass options when class instantiated
*/
this.construct(options);
};
现在我正在使用以下代码在一页中初始化我的类。
$(document).ready(function($){
var alcohol = new AlcoholOrder({ myVar : 'new Value' });
});
我想在点击事件触发时调用addRemoveFavorite
方法。目前,当我点击时出现错误
jquery-1.12.4.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function
我不知道如何在单击事件上调用类方法。我已经搜索过但没有得到正确的解决方案。
最佳答案
这不是 jQuery 特有的。问题在于您将 undefined
作为事件处理程序传递,因为您将 addRemoveFavorite
定义为局部变量,而不是自有或继承的属性。因此找不到 this.addRemoveFavorite
,并用 undefined
代替。
关于javascript - 面向对象 : jQuery class method call on click event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46708493/