我目前正在探索jQuery's plugin authoring和:
var methods = {
init : function(options) {
console.log(options);
return this.each(function() {
console.log(options);
});
}
};
教程说,为了保持可链接性(我可以使用),我应该返回 this.each()
。我看到调用 $('div').myPlugin({'test':'test'})
调用了 init 函数并记录在控制台 options
中。但是,我似乎没有在 return this.each()
中看到 options
。
有人能解释一下为什么会这样吗?这是正常行为吗?
最佳答案
jQuery 的 .each() 方法有一组预定义的参数,因此第一个参数将被视为当前元素的索引。因此“选项”将被替换为索引。不过,无需将“选项”移交给函数,当函数创建闭包时,它将自动可用。
return this.each(function() {
console.log(options);
});
提示:您实际上并没有返回 this.each() ...从技术上讲,您只是返回“this”
关于javascript - jquery插件教程困惑,看不到初始化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225545/