我一直在摆弄一些更多的 OO 类型 JS 和 jQuery;
因此,这意味着我可以创建一个对象的多个实例(废话)。但是我在使用 .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
fiddle (repl.it):https://repl.it/GQfD/2
抱歉,如果我的解释很糟糕..
最佳答案
您可以使用bind
,它创建一个预定义了上下文 (this
) 的函数,以及调用它时将传递的(部分)参数:
$(this.selectorButton).on('click', this.toggleIt.bind(this, 500));
然后还有第二个问题:当 Console
构造函数运行时,选择器按钮尚未创建,因此您必须将这行代码移至 init
中方法,在创建按钮后(请参阅 repl.it 上更新的 fiddle ),或者使用事件委托(delegate),如下所示:
$(document).on('click', this.selectorButton, this.toggleIt.bind(this, 500));
...只会在事件触发时验证选择器按钮是否是其原因。
关于javascript - jQuery 使用动态命名的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725705/