您的位置:首页技术文章
文章详情页

javascript - 关于jQuery插件开发,defaults 定义了一个对象为空的方法,在外部调用时如何向这个空的方法添加方法

【字号: 日期:2023-02-21 15:28:22浏览:46作者:猪猪

问题描述

这是一个自己写的一个简单插件,问题在下面代码中有注释

(function($, window, document, undefined) { // 创造一个公共变量来构建一个私有方法 var privateFunction = function() {// 不是很明白这个私有方法要如何使用,具体有什么用,找了一下资料也不是很明白 } var methods = {nTab: function(options) { return this.each(function() {// 关于 data() 有没有必要用在这里,我理解 data() 函数是用来保存插件默认没有的参数或方法用的。不知道这样理解对不对。和我预留一个onSomeEvent 函数来增加一些功能有什么区别?var $this = $(this);var defaults = { tabTitle: ’.product-tab-title li’, tabContent: ’.product-tab-content’, tabTitleState: ’active’, tabContentBlock: ’block’, tabContentNone: ’none’, eventType: ’click’, onSomeEvent: function() {} // 这个为空的方法我预留处理打算以后遇到需要添加功能的时候使用,但怎么弄都不知道具体的使用方法};var settings = $.extend({}, defaults, options);$this.find(settings.tabTitle).on(settings.eventType, function() { index = $(this).index(); $(this).addClass(settings.tabTitleState).siblings().removeClass(settings.tabTitleState); $(settings.tabContent).eq(index).addClass(settings.tabContentBlock).removeClass(settings.tabContentNone).siblings(settings.tabContent).addClass(settings.tabContentNone).removeClass(settings.tabContentBlock);}); });} }; $.fn.userInCommonUseJsPlugin = function() {var method = arguments[0];if(methods[method]) { method = methods[method]; arguments = Array.prototype.slice.call(arguments, 1);} else/* if( typeof(method) == ’object’ || !method ) { method = methods.init;} else */{ $.error( ’Method ’ + method + ’ does not exist on jQuery.pluginName’ ); return this;}return method.apply(this, arguments); }})(jQuery, window, document);

这是我外部调用时的代码

$(function(){ $(’.nTab’).userInCommonUseJsPlugin(’nTab’, {// 我想找这里写一个onSomeEvent: function() {}来增加插件没有的功能,该如何实现 });})

问题在上述代码里有注释,还望大神指教!!!

问题解答

回答1:

好久没写过jquery插件了,应该是用把外部添加值通过$.extend方法来拓充到内部

回答2:

已经找到其中一个答案了,关于回调函数的使用http://learn.jquery.com/plugi...

插件内回调函数写法

var defaults = { // We define an empty anonymous function so that // we don’t need to check its existence before calling it. onImageShow : function() {}, // ... rest of settings ... }; // Later on in the plugin: nextButton.on( 'click', showNextImage ); function showNextImage() { // Returns reference to the next image node var image = getNextImage(); // Stuff to show the image here... // Here’s the callback: settings.onImageShow.call( image );}

外部调用时使用回调函数

$( 'ul.imgs li' ).superGallery({ onImageShow: function() {$( this ).after( '<span>' + $( this ).attr( 'longdesc' ) + '</span>' ); }, // ... other options ...});

标签: JavaScript