jquery开发自定义的插件总结

时间:2023-03-09 02:32:30
jquery开发自定义的插件总结

1、第一种方式,有元素的插件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>不带参数的jquery插件开发</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
(function($){
$.fn.extend({
myPlugName:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
})(jQuery);
</script>
</head> <body>
<input type="button" value="点击我" id="btn" />
</body> <script type="text/javascript">
$("#btn").myPlugName();
</script>
</html>

2、直接拓展$ 符号

<script>
$.extend({
sayHello: function(name) {
console.log('Hello,' + (name ? name : 'Dude') + '!');
}
})
$.sayHello(); //调用
$.sayHello('Wayou'); //带参调用
</script>