简体   繁体   中英

JQuery function is not defined

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();
        }
    });
}

I would like to use slideUpComm as function that I include on different events but console return Uncaught ReferenceError: slideUpComm is not defined. How I should pass function to function ? Should I use callback?

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() {

});
}
}

My Object look like above.

The problem is slideUpComm is a member of an object... so you need to use the object reference to invoke the method

//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();
        }
    });
}

slideUpComm is a function of dateObj, you can not directly invoke the function. So to invoke a function you need to create an instance of function/object

var a = new dataObj();

then you can invoke the function using

a.slideUpComm()

Could this not be reduced to:

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

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM