编写jquery插件

来源:互联网 发布:js 双重级联 编辑:程序博客网 时间:2024/05/22 02:04

编写一个jQuery插件的原则:

  1. $.fn绑定函数,实现插件的代码逻辑;
  2. 插件函数最后要return this;以支持链式调用;
  3. 插件函数要有默认值,绑定在$.fn..defaults上;
  4. 用户在调用时可传入设定值以便覆盖默认值。

给jQuery对象绑定一个新方法是通过扩展$.fn对象实现的。

$.fn.highlight = function (options) {    // 合并默认值和用户设定值:    var opts = $.extend({}, $.fn.highlight.defaults, options);    this.css('backgroundColor', opts.backgroundColor).css('color', opts.color);    return this;}// 设定默认值:$.fn.highlight.defaults = {    color: '#d85030',    backgroundColor: '#fff8de'}

用户使用时,只需一次性设定默认值:

\$.fn.highlight.defaults.color = '#fff';\$.fn.highlight.defaults.backgroundColor = '#000';

然后就可以非常简单地调用highlight()了。

0 0