【发布时间】:2017-03-10 18:50:07
【问题描述】:
我一直在摆弄一些 OO 类型的 JS 和 jQuery;,因为这意味着我可以创建一个对象的多个实例(duh)。但是,我在使用 .click() 或 .on() 等中的对象函数和变量时遇到了问题。我看到了问题,我知道它是什么;我正在尝试在全局甚至特定对象中使用本地对象"this",而没有定义调用的方法。
代码
/* 导出的 cConsole */
var styleDiv = "position:absolute;min-width:100%;min-height:100%;z-index:200;top:0;display:none;padding-left:6px;border-left:6px solid red;background-color:lightgrey;";
var styleButton = "position:fixed;color:white;background-color:red;bottom:0px;right:0px;";
var cConsole = function(name, parent) {
this.name = name;
this.parent = parent;
if (this.name === undefined)
this.name = 'console';
if (this.parent === undefined)
this.parent = 'body';
this.selectorDiv = 'div[name="' + this.name + '"]';
this.selectorButton = 'button[name="' + this.name + '"]';
this.init = function() {
$(this.parent).after('<div style="' + styleDiv + '" name="' + this.name + '"></div>');
$(this.parent).after('<button style="' + styleButton + '" name="' + this.name + '">Toggle ' + this.name + '</button>');
$(this.selectorDiv).append('<button style="' + styleButton + '" name="' + this.name + '">Toggle ' + this.name + '</button>');
};
this.toggleIt = function(time) {
$(this.selectorDiv).toggle(time);
};
this.hideIt = function(time) {
$(this.selectorDiv).hide(time);
};
this.showIt = function(time) {
$(this.selectorDiv).show(time);
};
$(this.selectorButton).on('click', function() {
// I realize that 'this' is refering to the button object so this is fake.
// I just don't know how to pass in the object.
// I've tried setting 'var self = this' then using 'self.' as it was declared
// before this function but still not being called correctly as its still an
// object var.
SOMETHING POINTING TO THE "PARENT" OBJECT.toggleIt(500);
});
}
行数:41~50
小提琴(repl.it):https://repl.it/GQfD/2
对不起,如果我的解释很糟糕..
【问题讨论】:
-
请复制/粘贴问题正文中的代码,而不是指向 GitHub 上的文件 :)
标签: javascript jquery oop