简体   繁体   中英

Can't access javascript class from within jquery function

I have this function inside of a javascript class:

this.checkSections = function(){
        jQuery('#droppable #section').each( function() {
            nextId = jQuery(this).next().attr('id');
            if (nextId != 'small' && nextId != 'large'){
                jQuery(this).remove();
                this.sections --;
                this.followArticles = 0;
            }else{
                articles = 0;
                obj = jQuery(this).next();
                while (nextId == 'small' || nextId == 'large'){
                    articles++;
                    obj = obj.next()
                    nextId = obj.attr('id');
                    //alert(nextId);
                }
                this.followArticles = articles;
                alert(this.sections);
            }
        });
    }

the alert(this.sections); (last lines) gives output of undefined although the sections is defined and used.

what could be the problem?

this is always a local variable and therefore it is overwritten in every function.

What you might do is pointing to your class eg var myClass = this; and use myClass instead of this .

 this.checkSections = function(){

    var myClass = this;

    jQuery('#droppable #section').each( function() {
        nextId = jQuery(this).next().attr('id');
        if (nextId != 'small' && nextId != 'large'){
            jQuery(this).remove();
            myClass.sections --;
            myClass.followArticles = 0;
        }else{
            articles = 0;
            obj = jQuery(this).next();
            while (nextId == 'small' || nextId == 'large'){
                articles++;
                obj = obj.next()
                nextId = obj.attr('id');
                //alert(nextId);
            }
            myClass.followArticles = articles;
            alert(myClass .sections);
        }
    });
}

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