我是jQuery.so的新手,请告诉我如何在循环内使用this
变量。如何使用jQuery访问此内容?
对于如。
this.tblsize=10;
$.each([1,2],function(idx,val){
console.log(this.tblsize)
});
输出
undefined
undifined
但我需要得到输出10 10
。
有什么问题吗?
我是jQuery.so的新手,请告诉我如何在循环内使用this
变量。如何使用jQuery访问此内容?
对于如。
this.tblsize=10;
$.each([1,2],function(idx,val){
console.log(this.tblsize)
});
输出
undefined
undifined
但我需要得到输出10 10
。
有什么问题吗?
您不能使用这个inside
匿名函数,因为它是另一个范围。
这应该工作
this.tblsize=10;
var thisref = this;
$.each([1,2],function(idx,val){
console.log(thisref.tblsize)
});
只是不使用此功能,使用任何其他变量名:
var tblsize=10;
$.each([1,2],function(idx,val){
console.log(tblsize)
});
你需要利用closure为了从不同范围访问this
:
this.tblsize=10;
var self = this;
$.each([1,2],function(idx,val){
console.log(self.tblsize)
});
用下面的例子只是尝试:
<ul>
<li>foo</li>
<li>bar</li>
</ul>
$("li").each(function(index) {
console.log(index + ": "" + $(this).text());
});
我认为这可以帮助你解决你的问题。
在调用$ .each之前创建this
的副本。在$以内。每个this
将指代$.each()
的元素。
this.tblsize=10;
var $this = this;
$.each([1,2],function(idx,val){
console.log($this.tblsize)
});
让我们来看看你的代码:
this.tblsize = 10;
这里,tblsize
值一直$.each()
下一页范围超出了规定的,如果你这样做:
$.each([1,2],function(idx,val){
console.log(this)
});
您将获得像1
& 2
这样的值,因为this
这里指的是$.each()
方法的内部结果范围。所以,就你的情况而言,如果你做了类似this.tblsize
的事情,那么肯定会得到类似undefined
的东西,因为每个内部都没有这个名字的变量。
因此,要得到你想要的,你可以简单地创建一个圆形全局对象,外面的范围变量存储在它和访问它的$.each()
方法里面,像什么:
this.tblsize = 10;
// circular global object
var table_size = this;
$.each([1,2],function(idx,val){
console.log(table_size.tblsize); // way 1
console.log($(table_size)[0].tblsize); // way 2
});
这里面的[jQuery的可能重复每个循环](http://stackoverflow.com/questions/11070462/jquery-this-inside-each-loop) – Matt