jQuery扩展插件——$.extend(obj)与$.fn.extend(obj)

来源:互联网 发布:mac秋冬色号推荐 编辑:程序博客网 时间:2024/05/21 01:52
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<scriptsrc="jquery-1.11.1.min.js"></script>
</head>
<body>
<ul id="_ul">
<li>aaa</li>
<li>ccc</li>
<li>bbb</li>
</ul>
<div id="test"></div>
<script>
// (function($){
// $.fn.AlertSelf = function(){
// this.click(function(){alert($(this).html())});
// }
// })(jQuery)

// $('#_ul li').AlertSelf();

// var result = $.extend({},{name:'tom',age:21},{name:'jerry',sex:'boy'})
// console.log(result);
// $.extend({
// hello:function(){alert('hello');}
// })
// $.hello()
/* $.entend 是将方法合并到jquery的全局对象中, $.fn.extend 是将方法合并到jquery的实例对象中去 */
// $.fn.extend({
// hello:function(){alert('hello');}
// })
// $.extend({net:{}});
// $.extend($.net,{
// hellp:function(){alert('hello');}
// })
/* 1.定义一个全局函数*/
jQuery.foo =function(){
alert("全局");
}
jQuery.bar =function(){
alert("在一个全局");
}
/* 2.使用 extend 定义全局函数*/
jQuery.extend({
foo1:function(){alert("extend全局1");},
bar1:function(){alert("extend全局2");}
});

/* 3. 使用命名空间定义函数*/
jQuery.plugin = {
foo2:function(){
alert("使用namespace定义函数");
}
}
/*$(function(){
$.foo();
$.bar();
$.foo1();
$.bar1();
$.plugin.foo2();
})*/

/* 二、对象级别的插件开发*/

/* 形式一*/
(function($){
$.fn.extend({
foo3:function(){alert('队形级别extend1');},
bar3:function(){alert('对象那个级别extend2');}
})
})(jQuery);

/*形式二*/
(function($){
$.fn.foo4 =function(){
alert('队形级别fn方法');
}
})(jQuery);

/* 接受参数来控制插件的行为*/
(function($){
$.fn.bar4 =function(options){
var defaults = {aaa:'1',bbb:'2'};
var opts =$.extend(defaults,options);
alert('参数值:aaa:'+opts.aaa+';bbb:'+opts.bbb);
}
})(jQuery);

/* 提供公有方法访问插件的配置项值*/
(function($){
$.fn.foo5 =function(options){
var opts =$.extend({},$.fn.foo5.defaults,options);
alert('参数值:aaa:'+opts.aaa+';bbb:'+opts.bbb);
}
$.fn.foo5.defaults = {aaa:'1',bbb:'2'};
})(jQuery);

/* 提供公有方法来访访问插件中其他的方法 */
(function($){
$.fn.bar5 =function(options){
$.fn.bar5.alert(options);
}
$.fn.bar5.alert =function(params){
alert(params);
}
})(jQuery);

$(function(){
$('#test').foo3();
$('#test').bar3();
$('#test').foo4();
$('#test').bar4();
$('#test').bar4({aaa:'3'});
$('#test').bar4({aaa:'3',bbb:'4'});
$('#test').foo5();
$('#test').foo5({aaa:'5',bbb:'6'});
$('#test').bar5('aaaa');
})

</script>
</body>
</html>