2010-06-24 33 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>,并显示每个类的名称。