我正在创建我的第一个jQuery插件,以便轻松获取所需数据,而无需为不同元素重复相同的脚本。我希望我的插件可以得到以下内容:宽度,高度,位置以及更多指定元素和他的父级(我将需要它们稍后使用),例如:
$('element').myPlugin(); // will return all
$('element').myPlugin(width); // will return only width
$('element').myPlugin(width, height); // will return width and height
我不知道如何以适当的形式从插件中获取数据。我试图找出它但总是得到“未定义”或[对象对象]作为结果。如果有人可以举例说明我的“[[?]]”部分应该如何显示,我将不胜感激:
(function($){
$.fn.myPlugin = function(options) {
var defaults = {
width: this.width(),
height: this.height(),
parentWidth: this.parent().width(),
[[more]]
}
var options = $.extend(defaults, options);
return this.each(function () {
var $this = $(this);
[[?]]
};
})(jQuery);
答案 0 :(得分:0)
这样做的一种方法是将数据存储到元素“数据对象”中。这是代码:
$.fn.myPlugin = function(options) {
var defaults = {
width: this.width(),
height: this.height(),
parentWidth: this.parent().width(),
[[more]]
}
var options = $.extend(defaults, options);
return this.each(function () {
var $this = $(this);
var dimen = {width: width, height: height, ..}
$this.data('dimen', diemn);
};
};
现在应用你的插件:
$('selector').myPlaugin();
稍后您可以获取数据:
$('selector').data('dimen'); //will return the dimention object
可能有更好的方法来做到这一点。