javascript - 无法从 jquery 函数中访问 javascript 类

标签 javascript jquery oop

我在 javascript 类中有这个函数:

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

alert(this.sections);(最后几行)给出了undefined的输出,尽管sections已被定义和使用。

可能是什么问题?

最佳答案

this 始终是局部变量,因此它在每个函数中都会被覆盖。

您可能会做的是指向您的类(class),例如var myClass = this; 并使用 myClass 而不是 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);
        }
    });
}

关于javascript - 无法从 jquery 函数中访问 javascript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562471/

相关文章:

javascript - 选择了哪个垫菜单?

javascript - 计算和限制文本区域中的单词

javascript - 如何使用 javascript/jquery 突出显示所写的特定单词?

delphi - 如何检查一个类是否实现了一个接口(interface),并尊重超集?

c++ - 从基类扩展功能的派生类的最佳设计

javascript - 如何拦截promise请求?

javascript - 在同一模块中多次声明 AngularJS 服务

jQuery 没有定义?

javascript - 在backbone.js中添加两个事件

c++:多文件c++项目中的相互引用结构