【问题标题】:JQuery function is not defined未定义 JQuery 函数
【发布时间】:2014-01-03 15:01:36
【问题描述】:
this.slideUpComm = function (){
    $("#Day-events-content p").addClass("hidden").slideUp("fast");
} 
this.showhideEvents = function() {
    $("#Day-events-content").on("click", ".eventsToggle", function() {
        var obj = $(this).next();
        if ($(obj).hasClass("hidden")) {
            slideUpComm();
            $(obj).removeClass("hidden").slideDown();
        } else {
            $(obj).addClass("hidden").slideUp();
        }
    });
}

我想使用 slideUpComm 作为我包含在不同事件中的函数,但控制台返回 Uncaught ReferenceError: slideUpComm is not defined。 我应该如何将函数传递给函数?我应该使用回调吗?

function dateObj() {
this.d = new Date();
this.day = this.d.getDate();
this.numDay = this.d.getDay();
this.month = parseInt(this.d.getMonth());
this.year = this.d.getFullYear();

this.slideUpComm = function (){

} 
this.showhideEvents = function() {

});
}
}

我的对象如上所示。

【问题讨论】:

  • 什么是this,你是如何调用函数的?

标签: javascript jquery callback closures


【解决方案1】:

slideUpComm 是 dateObj 的函数,不能直接调用该函数。所以要调用一个函数,你需要创建一个函数/对象的实例

var a = new dataObj();

然后您可以使用

调用该函数
a.slideUpComm()

【讨论】:

  • @arun-p-johny 答案是正确的,当函数调用未添加到问题中时,我的答案是相关的
【解决方案2】:

这不能简化为:

$("<object>").slideToggle();

?

【讨论】:

  • 我认为它会更短更干净。
【解决方案3】:

问题是slideUpComm是一个对象的成员...所以你需要使用对象引用来调用方法

//create a closure varaible to hold the reference to the instance
var self = this;
this.slideUpComm = function (){
    $("#Day-events-content p").addClass("hidden").slideUp("fast");
} 
this.showhideEvents = function() {
    $("#Day-events-content").on("click", ".eventsToggle", function() {
        var obj = $(this).next();
        if ($(obj).hasClass("hidden")) {
            //slideUpComm is a instance property so access it using the instance
            self.slideUpComm();
            $(obj).removeClass("hidden").slideDown();
        } else {
            $(obj).addClass("hidden").slideUp();
        }
    });
}

【讨论】:

  • 谢谢你的帮助。请问我用这种方式在JS中创建obj是否合适?我的意思是最佳实践。
猜你喜欢
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多