javascript - 在 jQuery 中,this.each() 是如何工作的?

标签 javascript jquery jquery-plugins

为了让我的问题更具体,我阅读了 .each() for jQuery 的文档,但我有点困惑。我有这段代码:

$.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;

};

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

最佳答案

each 函数可以接受一个接受索引的函数作为参数,但它是可选的。

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

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

在 jQuery API 中有一个使用示例

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

引用资料 - http://api.jquery.com/each/

关于javascript - 在 jQuery 中,this.each() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106414/

相关文章:

jquery - goMap jquery插件重绘 map

javascript - 将流程图另存为 PDF

javascript - 从客户端了解容器中是否存在 blob

javascript - 使用 jquery 设置表列样式

jQuery 显示 5 一次列出一个列表

javascript - 粘贴时如何将url自动转换为超链接

javascript - RateIt jquery 插件与我项目中的 jquery 文件发生冲突?

javascript - Quasar Q-Table 如何获得过滤或排序的行?

javascript - Knockout 可观察数组不会重新呈现我的列表

javascript - 忽略 Safari 的初始页面加载 popstate