簡體   English   中英

原型 Class 中未定義的 DOM 元素

[英]Undefined DOM element in Prototype Class

我的目標是有一個按鈕,當點擊它時,它將創建一個 object,它通過使用切換和設置超時來閃爍,然后將 object 附加到 Html 上。 但是,我在 Javascript 代碼中收到“無法讀取未定義的屬性‘切換’”錯誤消息。

JS創建object

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 ,鏈接這個:

MakeSquare.prototype.repeat = function () {
  setTimeout(this.step.bind(this), this.time)
}

有關更多信息,請參閱問題和答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM