在jQuery中,this.each()如何工作?

ant*_*liu 6 javascript jquery jquery-plugins

为了使我的问题更具体,我阅读了关于jQuery的.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;
Run Code Online (Sandbox Code Playgroud)

};

现在我没有得到的是为什么每个函数都没有索引或元素?这段代码来自我试图阅读的jQuery插件.我也不太了解$ .fn.在顶部,我知道它代表原型,但究竟发生了什么?

Jam*_*ong 8

每个函数都可以接受一个索引作为参数的函数,但它是可选的.

为简单起见,.each实现了this引用当前元素.

但是,.each 可以接受索引作为其回调的参数.

在jQuery API中有一个使用示例

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});
Run Code Online (Sandbox Code Playgroud)

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