【问题标题】:Error when calling a function inside jQuery plugin在 jQuery 插件中调用函数时出错
【发布时间】:2012-11-14 08:03:18
【问题描述】:

我正在开发一个 jQuery 插件,当我单击暂停链接时,我需要在插件中调用一个函数。我的代码是这样的

$("#pauseAnimation").click(function () { $.fn.cjImageVideoPreviewer().pauseAnimation(); })

要调用的函数就是这个

(function ($) {
$.fn.cjImageVideoPreviewer = function (options) {

    var settings = {
        // user editable settings
        images: [],
        delay: 1000,
        autoPlay: false,
        showProgress: false
    };

    var sys = {
        // function parameters
        version: '1.0.2',
        elem: null,
        idx: 1,
        timer: null,
        loaded: 0,
        mouseX: null,
        mouseY: null,
        state: false
    };

    /*
        handle transitions
    ***************************************/

    function clearTimer() {
        if (sys.timer !== null) {
            window.clearTimeout(sys.timer);
            sys.timer = null;
        }
    }

    // reset everything
    function stopAnimation() {

        if (sys.state) {

            clearTimer();
            sys.idx = 0;
            sys.state = false;

            // show the first image
            $(sys.elem).find("div.cjImageVideoPreviewer img:first").css({
                "display": "block"
            });

            // hide all the other images
            $(sys.elem).find("div.cjImageVideoPreviewer img:not(:first)").css({
                "display": "none"
            });
        }
    }

    // pause
    function pauseAnimation() {

        if (sys.state) {

            clearTimer();
            sys.idx = 0;
            sys.state = false;
        }
    }

当我点击链接时出现错误

Microsoft JScript 运行时错误:对象不支持此属性或方法 任何帮助都会很明显..

【问题讨论】:

  • 你的cjImageVideoPreviewer 函数返回this,所以它是可链接的吗?
  • 您的插件是否公开了这些功能中的任何一个?
  • 您可能不想将其称为$.fn.cjImageVideoPreviewer().,而是称为$.cjImageVideoPreviewer().

标签: javascript jquery


【解决方案1】:

在 JQuery documentation 中创建插件的推荐方法是:

(function( $ ){

  var methods = {
     init : function( options ) {

       return this.each(function(){
         $(window).bind('resize.tooltip', methods.reposition);
       });

     },
     destroy : function( ) {

       return this.each(function(){
         $(window).unbind('.tooltip');
       })

     },
     reposition : function( ) { 
       // ... 
     },
     show : function( ) { 
       // ... 
     },
     hide : function( ) {
       // ... 
     },
     update : function( content ) { 
       // ...
     }
  };

  $.fn.tooltip = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

如果想使用这种方式创建自定义插件,您的插件应该看起来与此类似:

(function( $ ){
  var sys, settings;
  var methods = {
    init : function( options ) {
        //do stuf with options settings
     },
    clearTimer: function () {
        if (sys.timer !== null) {
            window.clearTimeout(sys.timer);
            sys.timer = null;
        }
    },
    stopAnimation: function () {

        if (sys.state) {

            clearTimer();
            sys.idx = 0;
            sys.state = false;

            // show the first image
            $(sys.elem).find("div.cjImageVideoPreviewer img:first").css({
                "display": "block"
            });

            // hide all the other images
            $(sys.elem).find("div.cjImageVideoPreviewer img:not(:first)").css({
                "display": "none"
            });
        }
    },
    pauseAnimation: function () {

        if (sys.state) {

            clearTimer();
            sys.idx = 0;
            sys.state = false;
        }
    }
  };

  $.fn.cjImageVideoPreviewer = function (method) {

    settings = {
        // user editable settings
        images: [],
        delay: 1000,
        autoPlay: false,
        showProgress: false
    };

    sys = {
        // function parameters
        version: '1.0.2',
        elem: null,
        idx: 1,
        timer: null,
        loaded: 0,
        mouseX: null,
        mouseY: null,
        state: false
    };

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.cjImageVideoPreviewer' );
    }    

 }
})( jQuery );

然后你可以像这样使用它:

//Init your plugin with some options
$('#pauseAnimation').cjImageVideoPreviewer({option1: 'value1', option2: 'value2'});
// then call a method like this:
$('#pauseAnimation').cjImageVideoPreviewer('pauseAnimation');

希望这能阐明如何开发 JQuery 插件。

【讨论】:

  • 我已经按照你说的做了,但是在 'pauseAnimation' sys.state 之类的函数上出现了错误,在那里无法访问 sys.state
  • 对不起,你是对的!我编辑了我的答案,以修复它。我忘记将 sys 和 settings vars 的声明移到 $.fn.cjImageVideoPreviewer 函数之外。现在它们在主匿名函数上声明。我还修复了一些其他“复制和粘贴”错误。
【解决方案2】:

您可能最好将嵌套函数分配给这样的变量:

(function($) { 
    $.fn.foo = function(options) {

        var do_stuff = function() {
            alert('do_stuff!')

            var do_other_stuff = function() {
                alert("do_other_stuff");
            };

            return {
                do_other_stuff: do_other_stuff
            };
        };

        return {
            do_stuff: do_stuff
        }
    };
})(jQuery);

$.fn.foo().do_stuff();
$.fn.foo().do_stuff().do_other_stuff();

享受吧!

编辑:

您也可以这样做:

$.fn.foo = {
    do_stuff : function() {
        alert("do_stuff!");
    }
};

$.fn.foo.do_stuff();

【讨论】:

  • 恐怕不行,你可以用不同的方式声明你的插件,我正在编辑我的帖子,你可以在一分钟内期待它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 2013-12-19
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
相关资源
最近更新 更多