为了扩展jQuery库函数,jQuery提供了两种方式
jQuery.extend(object)
- 扩展jQuery对象本身,主要是用来扩展jQuery全局函数 ,调用时直接$.函数名(参数)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
</head>
<body>
<script>
$.extend({
max:function(a,b) {
return (a > b) ? a: b;
},
min:function(a,b){
return (a < b) ? a: b;
}
});
console.log($.max(4,5));
console.log($.min(4,5));
</script>
</body>
</html>
结果
- 使用$调用max方法返回两个数的最大值,输出的结果为5,调用min方法返回两个数最小值输出为4
jQuery.fn.extend(object)
- 扩展 jQuery 元素集,主要用于扩展jQuery插件,调用时需要先创建jQuery对象,然后才能调用相应的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
</head>
<body>
<input type="checkbox" checked="checked" />乒乓球
<input type="checkbox" />足球
<input type="checkbox" />篮球
<input type="checkbox" />网球
<input type="checkbox" />橄榄球
<input type="checkbox" />高尔夫
<script>
jQuery.fn.extend({
check:function() {
this.attr("checked","checked");
},
uncheck:function() {
this.removeAttr("checked");
}
})
$("input[type='checkbox']").check();
</script>
</body>
</html>
结果
- 使用属性选择器,把所有的input标签中属性type="checkbox"的元素设置属性checked="checked”。
注意
- 为了避免自己定义的函数或者变量与外部冲突,对JQuery函数的扩展一般写在自执行匿名函数中。
比如下面的形式:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
</head>
<body>
<script>
(function($){
$.max=function(a,b){
return (a > b) ? a: b;
},
$.min=function(a,b){
return (a < b) ? a: b;
}
})(jQuery)
console.log($.max(4,5));
console.log($.min(4,5));
</script>
</body>
</html>
对于扩展 jQuery 元素集方式也写在自执行匿名函数中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.8.3.js" ></script>
</head>
<body>
<input type="checkbox" checked="checked" />乒乓球
<input type="checkbox" />足球
<input type="checkbox" />篮球
<input type="checkbox" />网球
<input type="checkbox" />橄榄球
<input type="checkbox" />高尔夫
<script>
(function($){
jQuery.fn.check = function(){
this.attr("checked","checked");
},
jQuery.fn.uncheck=function() {
this.removeAttr("checked");
}
})(jQuery)
$("input[type='checkbox']").check();
</script>
</body>
</html>