jQuery扩展机制

为了扩展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()

 

增加value的方法:
<!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>
发布了44 篇原创文章 · 获赞 5 · 访问量 3999

猜你喜欢

转载自blog.csdn.net/wangdada___/article/details/103140099