我有一个我正在创建的课程,当你有两个功能时,我很难理解如何使用this
。
在我的init函数中,this
引用了类对象,但在我的jQuery .each()
语句中,this
引用了您正在迭代的任何元素。因此,我将对类对象的引用保存在名为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
是我抓住的audio
标记的ID .each()
声明。
为什么我会遇到这个意外的时期错误?这是错误的做法吗?
我也试过这个:
tempThis.notes[$(this).id] = $(this).id + " note";
但我仍然在tempThis
之后收到错误。
答案 0 :(得分:2)
.each()
期望一个函数作为参数,您在function()
行中缺少each()
$.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
的变量键属性,使用括号表示法,如上所示