繁体   English   中英

Javascript&jQuery-了解“此”上下文-意外的“。”时期

[英]Javascript & jQuery - Understanding “this” Context - unexpected “.” period

我有一个类我创建,而我无法理解如何使用this ,当你深的东西两个功能。

在我的init函数中, this是指类对象,但是在我的jQuery .each()语句中, this.each()迭代的任何元素。 因此,我将对类对象的引用保存在名为tempThis的变量中。 但这会导致错误:

$.Audio = function() {}

$.Audio.prototype = {
  init: function() {
    this.notes = {};
    var tempThis = this;
    $('audio').each({
      // I'm getting an "Unexpected Token ." on this line
      // Right after tempThis
      tempThis.notes.$(this).id = $(this).id + " note";
    })
  }
}

这个想法是this.notes包含一个带有key: value对的对象,例如{ 'C': 'C note'} ,其中C是我在.each()语句中获取的audio标签的ID。

为什么会出现此意外期错误? 这是错误的方法吗?

我也尝试过这个:

tempThis.notes[$(this).id] = $(this).id + " note";

但是我在tempThis之后仍然收到错误。

.each()需要一个函数作为参数,因此在each()行中缺少function()

$.Audio = function () {}

$.Audio.prototype = {
    init: function () {
        this.notes = {};
        var tempThis = this;
        $('audio').each(function () {//missing function() here
            tempThis.notes[this.id] = this.id + " note";
        })
    }
}

另外,要访问音频元素的ID,您还需要使用this.id$(this).prop('id') ,并访问tempThis.notes的可变键属性。请tempThis.notes如上所示,请使用方括号表示法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM