您的位置:首页 > Web前端 > JQuery

jquery插件机制

2017-02-22 00:00 141 查看
摘要: 使用extend制作插件,丰富jquery对象或jquery元素集

一,jquery.fn.extend(object)

扩展 jQuery 元素集来提供新的方法(通常用来制作插件),需要指定dom对象调用

示例:

给input对象增加两个插件方法,jquery.fn.extend代码单独作为通用的插件文件common/check.js,在需要用此功能的地方引入$Import("common.check");

jQuery插件代码:

(function($) {
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
})(jQuery);

使用:

$Import("common.check");
$(function () {
$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();
});


二,jquery.extend(object)

作用:扩展jQuery对象本身,用来在jQuery命名空间上增加新函数。

示例:给input对象增加两个插件方法,jquery.extend代码单独作为通用的插件文件common/compare.js,在需要用此功能的地方引入$Import("common.compare");

jQuery插件代码:

(function($) {
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
})(jQuery);

使用:

$Import("common.compare");
$(function(){
jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5
});

以上均是作为插件使用,也可以直接在一个js文件中引用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: