与子方法共享对象参数 我正在研究jQuery插件,并在中间堆栈。应该很简单,但我就是找不到解决办法
以下是我所拥有的:与子方法共享对象参数 我正在研究jQuery插件,并在中间堆栈。应该很简单,但我就是找不到解决办法,jquery,Jquery,以下是我所拥有的: (function ($, undefined) { $.fn.myplug = function (options) { return this.append($("<p/>").text(option.text + " initiated")); } $.fn.myplug.ext = function () { //here I want read options from myplug (aft
(function ($, undefined) {
$.fn.myplug = function (options) {
return this.append($("<p/>").text(option.text + " initiated"));
}
$.fn.myplug.ext = function () {
//here I want read options from myplug (after running myplug first)
//and this.attr("id") which should give me #mydiv (how do i accomplish this)
return this.append("---" + option.text + "after initiation")
}
}(jQuery));
$(document).ready(function () {
var args={text:"myvar"};
$("#mydiv").myplug(args);
$("#mydiv").myplug.ext();
});
(函数($,未定义){
$.fn.myplug=函数(选项){
返回此.append($(“”).text(option.text+“initiated”);
}
$.fn.myplug.ext=函数(){
//这里我想从myplug中读取选项(首先运行myplug之后)
//还有这个.attr(“id”),它应该给我#mydiv(我如何实现这一点)
返回此.append(“--”+option.text+”启动后)
}
}(jQuery));
$(文档).ready(函数(){
var args={text:“myvar”};
$(“#mydiv”).myplug(args);
$(“#mydiv”).myplug.ext();
});
html:
实现这些的最佳实践是什么,我真的找不到合适的名称来搜索这个。
谢谢
编辑
jquery术语中的ext是什么意思,我将其命名为sub方法,但不确定您是否可以通过plugin init函数中的
.data
将所需内容附加到元素。后续分机调用可以读取该数据:
(function($) {
$.fn.myplug = function (options) {
var self = this;
$(self).data('myplug', options);
return {
ext:function () {
$(self).text(
$(self).data('myplug').title
);
}
}
}
})($);
$("#foo").myplug({title:'there'})
$("#foo").myplug().ext()
扩展方法应该使用
myplug()
,而不仅仅是myplug
,以支持正确的作用域。通常的jQuery模式是将扩展名作为第一个参数传递,如myplug('ext',…)
只有附加到$的函数。fn
对象将正确引用所需的this
(元素)范围
通过使用,您实际上是在扩展先前定义的函数本身
最佳实践是使用jQuery推荐的插件开发指南
例如,你会找到一些关于它的信息
// Plugin definition.
$.fn.hilight = function( options ) {
// Iterate and reformat each matched element.
return this.each(function() {
var elem = $( this );
// ...
var markup = elem.html();
// Call our format function.
markup = $.fn.hilight.format( markup );
elem.html( markup );
});
};
// Define our format function.
$.fn.hilight.format = function( txt ) {
return "<strong>" + txt + "</strong>";
};
如果你展示一个很小的例子来修补,可以吗it@INgeeg:添加了一个示例,因此无法从ext引用对象。参数呢
// Plugin definition.
$.fn.hilight = function( options ) {
// Iterate and reformat each matched element.
return this.each(function() {
var elem = $( this );
// ...
var markup = elem.html();
// Call our format function.
markup = $.fn.hilight.format( markup );
elem.html( markup );
});
};
// Define our format function.
$.fn.hilight.format = function( txt ) {
return "<strong>" + txt + "</strong>";
};
var $el = $(".element");
$el.hilight.format.call($el);