jQuery插件开发-类级别的插件开发

jQuery插件的开发包括两种:一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级别的插件开发,即给jQuery对象添加方法。下面是jQuery类级别插件开发详细的说明。

类级别的插件开发最直接的理解就是给jQuery类添加类方法,可以理解为添加静态方法。典型的例子就是$.AJAX()这个函数,将函数定义于jQuery的命名空间中。关于类级别的插件开发可以采用如下几种形式进行扩展:

1.1 添加一个新的全局函数
添加一个全局函数,我们只需如下定义:

jQuery.foo = function() {
  alert('This is a test. This is only a test.');
};

1.2 增加多个全局函数
添加多个全局函数,可采用如下定义:

jQuery.foo = function() {
  alert('This is a test. This is only a test.');
};
jQuery.bar = function(param) {
  alert('This function takes a parameter, which is "' + param + '".');
};

调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');
1.3 使用jQuery.extend(object);

jQuery.extend({
  foo: function() {
  alert('This is a test. This is only a test.');
},
bar: function(param) {
  alert('This function takes a parameter, which is "' + param +'".');
}
});

1.4 使用命名空间
虽然在jQuery命名空间中,我们禁止使用了大量的javaScript函数名和变量名。但是仍然不可避免某些函数或变量名将于其他jQuery插件冲突,因此我们习惯将一些方法封装到另一个自定义的命名空间。

jQuery.myPlugin = {
  foo:function() {
  alert('This is a test. This is only a test.');
},
bar:function(param) {
  alert('This function takes a parameter, which is "' + param + '".');
}
};

采用命名空间的函数仍然是全局函数,调用时采用的方法:

$.myPlugin.foo();
$.myPlugin.bar('baz');

通过这个技巧(使用独立的插件名),我们可以避免命名空间内函数的冲突。

posted @ 2015-01-12 21:18  delmarks  阅读(218)  评论(0编辑  收藏  举报