2013-10-20 42 views
0

開發一個小插件,我發現了一個問題,在裏面撕裂我。要叫我的插件,我使用:

$('#input').myPlugin(); 

在一個特定的時刻,我需要用我的插件的每一個裏面,下面是代碼:

var list = [] 
var str = 'just a test <b>foo</b> blablabla <b>bar</b>' 
str.children('b').each(function(i){ 
    // Here I want use the $(this) of each function 
    list.append($(this).text()) 
}) 

這段代碼我需要使用後另一個「每個」功能,但現在我不想使用「每個」的$(this),我想使用「global this」。換句話說,現在我想引用$('#input'),這是調用我的插件的元素。

hashtag.each(function(i)){ 

     // In the first "this" I want refer to $('input'), in the second, to this of each function. 
     $(this).functionToFindText($(this)) 
} 

我如何告訴jQuery這是什麼意思?

回答

2

聲明.each循環之前的變量var $this = $(this),並在內部回調中引用$this

+0

我不知道這是否是最好的方式來做到這一點,但是這種方式可行,而您的答案是獨一無二的,所以非常感謝! – Paladini

+1

這是最常用的方法。沒關係。 –