【问题标题】:In jQuery, how does the this.each() work?在 jQuery 中,this.each() 是如何工作的?
【发布时间】:2010-06-24 00:04:03
【问题描述】:

为了让我的问题更具体,我阅读了 .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;

};

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

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

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

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

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

    在 jQuery API 中有一个使用示例

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

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

    【讨论】:

    • 但是看第三行代码:this.each(function() {。具体来说,this.each( 在做什么?我怀疑它是否相同,因为我们没有看到 this 被包装为 jQuery 对象。
    【解决方案2】:

    它不需要索引,因为this 提供了上下文。正如docs 所指出的,“也可以通过 this 关键字访问该值。”这是通过使用call 完成的。比如:

    userFunction.call(valueOfElement, indexInArray, valueOfElement);
    

    $.fn.imgAreaSelect = function (options) 表示该函数正在添加到原型中。这允许它与 jQuery 对象的任何实例一起使用。

    【讨论】:

      【解决方案3】:

      $.each(fn) 为当前上下文中包含的每个元素调用fn。每次调用fn 时,都会将“当前”元素作为this 传递。

      所以在下面的例子中:

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

      会为 DOM 中的每个<div> 弹出一个警报,并显示每个的类名。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 1970-01-01
        • 2011-02-10
        • 2011-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多