【问题标题】:OOP : jQuery class method call on click eventOOP:点击事件的jQuery类方法调用
【发布时间】:2017-10-12 11:31:33
【问题描述】:

我是 jQuery 中的 OOP 新手。

我有以下课程

/*
 * 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 未捕获类型错误: ((n.event.special[g.origType] || {}).handle || g.handler).apply 不是 一个函数

我不知道如何在点击事件上调用类方法。我已经搜索但没有得到正确的解决方案。

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    这不是 jQuery 特有的。问题是您将undefined 作为事件处理程序传递,因为您将addRemoveFavorite 定义为局部变量,而不是拥有或继承的属性。所以this.addRemoveFavorite没有找到,undefined被替换了。

    【讨论】:

    • 哦,是的。那是我的错误。感谢@llama 指导我。
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 2012-05-17
    • 2018-08-31
    • 2012-03-24
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多