您的位置:首页 > Web前端 > JQuery

jquery 插件开发

2015-07-20 14:45 711 查看
一、$.extend() 这种方式用来定义一些辅助方法是比较方便的

$.extend({
sayHello:function(name){
console.log('Hello:'+name);
}
});

$.sayHello("张三");//调用


二、$.fn

$.fn.myPlugin=function(){
//在这里面,this指的是用jQuery选中的元素
//例如 :$('a'),则this=$('a')
this.css('color','red');
this.each(function(){
$(this).append(': '+$(this).attr('href'));
});
}

//支持链式调用
$.fn.myPlugin = function() {
//在这里面,this指的是用jQuery选中的元素
this.css('color', 'red');
return this.each(function() {
//对每个元素进行操作
$(this).append(' ' + $(this).attr('href'));
})
}

//传递参数
$.fn.myPlugin = function(options) {
var defaults = {
'color': 'red',
'fontSize': '12px'
};
var settings = $.extend(defaults, options);
return this.css({
'color': settings.color,
'fontSize': settings.fontSize
});
}
//保护默认参数 的 方法
$.fn.myPlugin = function(options) {
var defaults = {
'color': 'red',
'fontSize': '12px'
};
var settings = $.extend({},defaults, options);//将一个空对象做为第一个参数
return this.css({
'color': settings.color,
'fontSize': settings.fontSize
});
}
//面向对象+用自调用匿名函数包裹你的代码
//定义Beautifier的构造函数
(function() {
var Beautifier = function(ele, opt) {
this.$element = ele,
this.defaults = {
'color': 'red',
'fontSize': '12px',
'textDecoration':'none'
},
this.options = $.extend({}, this.defaults, opt)
}
//定义Beautifier的方法
Beautifier.prototype = {
beautify: function() {
return this.$element.css({
'color': this.options.color,
'fontSize': this.options.fontSize,
'textDecoration': this.options.textDecoration
});
}
}
//在插件中使用Beautifier对象
$.fn.myPlugin = function(options) {
//创建Beautifier的实体
var beautifier = new Beautifier(this, options);
//调用其方法
return beautifier.beautify();
}
})();


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: