原型 Class 中未定义 DOM 元素
Undefined DOM element in Prototype Class
我的目标是拥有一个按钮,当单击该按钮时,它会创建一个闪烁的对象,方法是使用切换和设置超时,然后将该对象附加到 Html。但是,我在 Javascript 代码中收到“无法读取未定义的 属性 'toggle'”错误消息。
JS创建对象
var MakeSquare = function (top, left, time) {
this.time = time;
this.$node = $('<span class="square"></span>');
this.setPosition(top, left);
this.repeat();
}
// this function will set the position of the <span> on the webpage
MakeSquare.prototype.setPosition = function (top, left) {
var styleSettings = {
top: top,
left: left
};
this.$node.css(styleSettings);
};
// this function will toggle the <span> off, and invoke the repeat function to turn it back on again, and so forth.
MakeSquare.prototype.step = function() {
this.$node.toggle();
this.repeat();
}
MakeSquare.prototype.repeat = function () {
setTimeout(this.step, this.time)
}
这是 this
失去上下文时出现的标准问题。
尝试使用 bind
、link 这个:
MakeSquare.prototype.repeat = function () {
setTimeout(this.step.bind(this), this.time)
}
有关详细信息,请参阅 this 问题和答案。
我的目标是拥有一个按钮,当单击该按钮时,它会创建一个闪烁的对象,方法是使用切换和设置超时,然后将该对象附加到 Html。但是,我在 Javascript 代码中收到“无法读取未定义的 属性 'toggle'”错误消息。
JS创建对象
var MakeSquare = function (top, left, time) {
this.time = time;
this.$node = $('<span class="square"></span>');
this.setPosition(top, left);
this.repeat();
}
// this function will set the position of the <span> on the webpage
MakeSquare.prototype.setPosition = function (top, left) {
var styleSettings = {
top: top,
left: left
};
this.$node.css(styleSettings);
};
// this function will toggle the <span> off, and invoke the repeat function to turn it back on again, and so forth.
MakeSquare.prototype.step = function() {
this.$node.toggle();
this.repeat();
}
MakeSquare.prototype.repeat = function () {
setTimeout(this.step, this.time)
}
这是 this
失去上下文时出现的标准问题。
尝试使用 bind
、link 这个:
MakeSquare.prototype.repeat = function () {
setTimeout(this.step.bind(this), this.time)
}
有关详细信息,请参阅 this 问题和答案。