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

前端之家收集整理的这篇文章主要介绍了javascript – 在jQuery中,this.each()如何工作?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为了使我的问题更具体,我阅读了关于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;

};

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

解决方法

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

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

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

在jQuery API中有一个使用示例

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

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

原文链接:https://www.f2er.com/jquery/152961.html

猜你在找的jQuery相关文章