jQuery中的javascript'this'范围 [英] javascript 'this' scope in jQuery
问题描述
我刚刚将一段代码从对象文字转换为类,并且在jQuery $.each()
循环中遇到了作用域问题.
I have just converted an piece of code that was an object literal to a class and am having problems with the scope in a jQuery $.each()
loop.
说我上课...
var myClass = function(var1) {
this.var1 = var1;
}
myClass.prototype.myFuncion = function() {
var context = this;
$.each(this.var1, function() {
context.myOtherFunction()
//is there any way of accessing 'this' from here?
})
}
我想知道如何从每个内部访问类上下文?
I want to know how to access the class context from within the each?
我知道我可以在循环外定义变量,但这是首选方法吗?
I know I can define a variable outside of the loop but is this the preferred method?
推荐答案
在jQuery each
中,this
关键字引用迭代中的当前元素.
您可以阅读文档并查看
In jQuery each
, the this
keyword refers to the current element in the iteration.
You can read the documentation and see examples to illustrate this.
Defining a variable outside the loop is common case, as you can see, for instance, in jQuery-UI source code for datepicker.
这篇关于jQuery中的javascript'this'范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!