jquery插件教程令人困惑,无法看到init参数

时间:2012-02-10 09:29:38

标签: javascript jquery

我正在探索jQuery's plugin authoring和:

var methods = {
    init : function(options) {
        console.log(options);
        return this.each(function() {
            console.log(options);
        });
    }
};

教程说要维护可链接性(我可以使用),我应该return this.each()。我看到调用$('div').myPlugin({'test':'test'})调用init函数并登录控制台options。但是,我似乎没有在options内看到return this.each()

有人可以解释为什么会这样吗?这是正常行为吗?

1 个答案:

答案 0 :(得分:2)

jQuery的.each()方法有一组预定义的参数,因此第一个参数将被视为当前元素的索引。所以“选项”将被索引取代。没有必要将“选项”移交给函数,但是,当函数创建闭包时,它将自动可用。

return this.each(function() {
    console.log(options);
});

提示:你实际上并没有返回this.each()......技术上你刚刚返回“this”