2010-06-24 30 views
6

爲了讓我的問題更加具體,我閱讀了關於.each()的jQuery文檔,但我有點困惑。我有這樣的代碼:在jQuery中,this.each()是如何工作的?

$.fn.imgAreaSelect = function (options) { 
options = options || {}; 

this.each(function() { 
    if ($(this).data('imgAreaSelect')) { 
     if (options.remove) { 
      $(this).data('imgAreaSelect').remove(); 
      $(this).removeData('imgAreaSelect'); 
     } 
     else 
      $(this).data('imgAreaSelect').setOptions(options); 
    } 
    else if (!options.remove) { 
     if (options.enable === undefined && options.disable === undefined) 
      options.enable = true; 

     $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options)); 
    } 
}); 

if (options.instance) 
    return $(this).data('imgAreaSelect'); 

return this; 

};

現在我不明白這是爲什麼每個函數都沒有索引或元素?這段代碼來自我試圖閱讀的jQuery插件。我也不太瞭解$ .fn。在頂部,我知道它代表原型,但是到底發生了什麼?

回答

8

每個函數都可以接受一個接受索引作爲參數的函數,但它是可選的。

爲簡單起見,.each被實現爲具有this引用當前元素。

但是,.each可以接受索引作爲它的回調參數。

有jQuery的API在使用的例子

$('li').each(function(index) { 
    alert(index + ': ' + $(this).text()); 
}); 

參考 - http://api.jquery.com/each/

+0

但看看第三行的代碼:)'this.each(函數({'這一點。具體來說,是什麼'this.each('做?我懷疑它是一樣的,因爲我們沒有看到'this'被封裝爲一個jQuery對象。 – AjaxLeung 2015-08-25 06:58:03

2

它不需要索引,因爲this提供了上下文。正如docs所述,「該值也可以通過此關鍵字訪問。」這是通過使用call來完成的。類似於:

userFunction.call(valueOfElement, indexInArray, valueOfElement); 

$.fn.imgAreaSelect = function (options)表示功能正在添加到原型中。這使它可以用於jQuery對象的任何實例。

2

$.each(fn)對當前上下文中包含的每個元素調用fn。每次調用fn時,它都會傳遞「當前」元素this

所以在下面的例子:

$("div").each(function() { 
    alert(this.className); 
}); 

會彈出一個警告在DOM每個<div>,並顯示每個類的名稱。