为了扩展jQuery库函数,有两种方式
①jQuery.extend(object):扩展jQuery对象本身,全局函数,调用时可以直接$.f()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>插件机制</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
$.extend({
min: function(a, b) {
return a < b ? a : b;
},
max: function(a, b) {
return a > b ? a : b;
}
});
var min = $.min(1,2);
console.log(min);
var max = $.max(1,2);
console.log(max);
</script>
</head>
<body>
</body>
</html>
②jQuery.fn.extend(object):扩展jQuery元素集(就是增加jQuery元素的函数),主要用于扩展jQuery插件,调用时需要先引用jQuery对象调用函数,如$().f()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="h" value="1"/>1
<input type="checkbox" name="h" value="2"/>2
<input type="checkbox" name="h" value="3"/>3
<input type="checkbox" name="h" value="4"/>4
<input type="button" value="点击" οnclick="t()"/>
</form>
<script>
jQuery.fn.extend({
values:function(){
var result="";
this.each(function(){
if(this.checked){
result=result+","+this.value;
}
});
result=result.substring(1);
return result;
}
})
function t(){
var result = $("[name='h']").values();
console.log(result);
}
</script>
</body>
</html>