【发布时间】:2015-03-07 20:54:03
【问题描述】:
我试图用 AMD 模式制作一个 jquery 插件,但似乎我无法让 each() 循环。它只返回 第一个 项目,但我有三个项目。
index.html,
<body>
<div class="element">
1
</div>
<div class="element">
2
</div>
<div class="element">
3
</div>
</body>
在html中head,
$(document).ready(function(){
$(".element").plugin2().data('plugin_plugin2').someMethod();
});
plugin.js,
!function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function($) {
var pluginName = 'plugin2',
defaults = {
param1: 'param1',
param2: 'param2'
};
var Plugin = function(element, options) {
this.element = element;
this.options = options;
};
Plugin.prototype = {
constructor: Plugin,
someMethod: function(options) {
var rootScope = this;
return rootScope.element.each(function(e){
console.log(e); // you get 0 only
console.log(this); // the first <div class="element"> only
});
}
};
$.fn[pluginName] = function(options) {
options = $.extend(true, {}, defaults, options);
return this.each(function() {
var $this = $(this);
$this.data('plugin_' + pluginName, new Plugin($this, options));
});
};
$.fn[pluginName].defaults = defaults;
$.fn[pluginName].Plugin = Plugin;
});
任何想法我做错了什么?
【问题讨论】:
标签: javascript jquery each js-amd jquery-1.9