【问题标题】:Jquery Plugin / Set interval and scoping issueJquery插件/设置间隔和范围问题
【发布时间】:2011-11-02 23:07:22
【问题描述】:

我正在尝试编写一个简单的 JQuery 插件来执行以下操作——我需要传入单个元素,例如 $("div").applyPlugin();然后让它遍历我传入的每个选择器,并设置一个本地 div 实例的间隔,然后在一段时间后将其清除。我正在尝试编写一个插件来帮助完成此任务,但似乎存在范围问题,我不确定发生了什么。

再次,我需要在一个 div 上设置一个计时器,并且能够在一个页面上重复使用它 10 次。所有 div 本质上都有自己的“计时器”,当您将鼠标重新悬停在 div 上时,它会自行清除该计时器。鼠标关闭,重新启动计时器等。

我不确定这是否必须使用插件的内部方法来完成,或者是否有更好/更简单的方法来做到这一点。

这是我目前的情况- '

(function( $ ){

var methods = {
    init : function( options ) { 
        /* init method */
        return setInterval( $(this).boxit('update'),5000);  
    },
    show : function( ) {    },
    hide : function( ) {  },
    update : function( content ) { 
        /* update method */
        console.log("ping");
    }
};

$.fn.boxit = function( method ) {
    // Method calling logic
    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 );

'

【问题讨论】:

    标签: javascript jquery html scope


    【解决方案1】:

    我可能走错了方向,如果这不是你想要的,请原谅我,但你可以将 jQuery 对象的引用作为参数传递。

    (function( $ ){
    
    var methods = {
        init : function( jqObject, options ) { 
            /* init method */
            return setInterval( jqObject.boxit('update'),5000);  
        },
        show : function( ) {    },
        hide : function( ) {  },
        update : function( content ) { 
            /* update method */
            console.log("ping");
        }
    };
    
    $.fn.boxit = function( method ) {
        var args = Array.prototype.slice.call( arguments, 0 );
        args.splice(0, 0, $(this));
    
        // Method calling logic
        if ( methods[method] ) {
            return methods[ method ].apply( this, args.slice( 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, args );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
        }           
    };
    
    })( jQuery );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多