栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用方法创建jQuery插件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用方法创建jQuery插件?

根据jQuery插件创作页面(http://docs.jquery.com/Plugins/Authoring),最好不要混淆jQuery和jQuery.fn命名空间。他们建议这种方法:

(function( $ ){    var methods = {        init : function(options) {        },        show : function( ) {    },// IS        hide : function( ) {  },// GOOD        update : function( content ) {  }// !!!    };    $.fn.tooltip = function(methodOrOptions) {        if ( methods[methodOrOptions] ) { return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) { // Default to "init" return methods.init.apply( this, arguments );        } else { $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );        }        };})( jQuery );

基本上,您将函数存储在数组中(作用域为包装函数),并检查输入的参数是否为字符串,如果参数为对象(或为null),则返回默认方法(此处为“ init”)。

然后您可以像这样调用方法…

$('div').tooltip(); // calls the init method$('div').tooltip({  // calls the init method  foo : 'bar'});$('div').tooltip('hide'); // calls the hide method$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

Javascripts“ arguments”变量是所有传递的参数的数组,因此它可以与任意长度的函数参数一起使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575065.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号