新建一个js文件,命名为MyCustomJq.js
(function () {
//定义插件的名称,例MyCustomJq
$.fn.MyCustomJq = function (options) {
// options如果为string格式,则转入对应的同名函数
if (typeof options == "string") {
return $.fn.MyCustomJq.methods[options](this);
}
// 设置默认属性、样式
var defaultOptions = {
name: 'L',
age: 20
};
// 获取传入的参数
var o = $.extend(defaultOptions, options);
var html = 'name = ' + o.name + ' , age = ' + o.age;
// 将需要改变的内容放入调用的控件呢
$(this).append(html);
}
//方法
$.fn.MyCustomJq.methods = {
alertMsg: function (jq) {
return jq.each(function () {
alertMsg(jq);
});
}
};
function alertMsg(target) {
// 可操作当前对象
}
})();
页面引入jq文件与我们写好的插件文件:
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="/Scripts/libs/jquery.js"></script>
<script src="/Admin/js/MyCustomJq.js"></script>
</head>
<body>
<!--添加一个div容易,用于插件操作-->
<div id=""divTest></div>
</body>
调用时代码:
<script>
$(document).ready(function () {
$('#divTest').MyCustomJq({
name : 'zhao yun'
});
$('#divTest').MyCustomJq('alertMsg');
})
</script>
运行效果: