制作高质量的JQuery Plugin 插件的方法

2019-06-06 09:53:51于海丽

//
// plugin definition
//
$.fn.hilight = function(options){
debug(this);
//build main options before element iteration
var opts = $.extend({}, $.fn.hilight.defaults, options);
//iterate and reformat each matched element
return this.each(function(){
$this = $(this);
//build element specific options
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
//update element styles
$this.css({
backgroundColor: o.background,
color: o.foreground
});
var markup = $this.html();
//call our format function
});
}
//
// private function for debugging
//
function debug($obj){
if(window.console && window.console.log){
window.console.log('hilight selection count: ' + $obj.size());
}
};
//
// define and expose our format function
//
$.fn.hilight.format = function(txt){
return '<strong>' + txt + '</strong>';
};
//
// plugin defaults
//
$.fn.hilight.defaults = {
foreground : 'red',
background : 'yellow'
};
//
// end of clousure
//
})(jQuery);

转载请注明出处http://samlin.cnblogs.com
比较希望大家开发jquery plugin的时候可以在最后把方法开放出来
return {
method1: funcion() {},
method2: funcion() {}
}

这样我们在使用的时候就可以用如下方式调用
var plugin = $("<div/>").plugin();
plugin.mehtod1();
plugin.method2();