2013-01-07 56 views
0

我是jQuery.so的新手,請告訴我如何在循環內使用this變量。如何使用jQuery訪問此內容?

對於如。

this.tblsize=10; 
$.each([1,2],function(idx,val){ 
console.log(this.tblsize) 
}); 

輸出

undefined 
undifined 

但我需要得到輸出10 10

有什麼問題嗎?

+0

這裏面的[jQuery的可能重複每個循環](http://stackoverflow.com/questions/11070462/jquery-this-inside-each-loop) – Matt

回答

0

您不能使用這個inside匿名函數,因爲它是另一個範圍。

這應該工作

this.tblsize=10; 
    var thisref = this; 

    $.each([1,2],function(idx,val){ 
    console.log(thisref.tblsize) 
    }); 
1

只是不使用此功能,使用任何其他變量名:

var tblsize=10; 
$.each([1,2],function(idx,val){ 
console.log(tblsize) 
}); 
1

你需要利用closure爲了從不同範圍訪問this

this.tblsize=10; 
var self = this; 
$.each([1,2],function(idx,val){ 
    console.log(self.tblsize) 
}); 
0

用下面的例子只是嘗試:

<ul> 
    <li>foo</li> 
    <li>bar</li> 
</ul> 

$("li").each(function(index) { 
    console.log(index + ": "" + $(this).text()); 
}); 

我認爲這可以幫助你解決你的問題。

0

在調用$ .each之前創建this的副本。在$以內。每個this將指代$.each()的元素。

this.tblsize=10; 
var $this = this; 
$.each([1,2],function(idx,val){ 
    console.log($this.tblsize) 
}); 

http://api.jquery.com/each/

0

讓我們來看看你的代碼:

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 
});