【问题标题】:jQuery Name Spacing and setTimeoutjQuery 名称间距和 setTimeout
【发布时间】:2012-07-22 18:04:03
【问题描述】:

我正在尝试根据此处的方向使用名称间距构建一个 jQuery 插件: http://docs.jquery.com/Plugins/Authoring#Namespacing

现在我遇到了一个问题,我的插件需要使用 setTimeout 来触发其中一个方法,

var jScrollerMethods = {
    ready:function(){
        return this.each(function(){
        var self = this,
    $this = $(this),
        data = $this.data('jScroller');

        settings.timeoutHandle = setTimeout(function(){
            if(settings.direction = "left"){
                this.moveLeft();
            }else if(settings.direction = "right"){
                this.moveRight();
            }
        }, settings.time);

        $this.data('jScroller', {
            settings: settings,
            element: this
        });
    });
}
$.fn.jScroller = function(call){
    if ( jScrollerMethods[call] ) {
      return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof call === 'object' || ! call ) {
        if (call) { $.extend(settings, call); }
        return jScrollerMethods.init.apply( this, call );
    } else {
        $.error( 'Method ' +  call + ' does not exist on jQuery.jScroller' );
    } 
}

但是我虽然会发生 setTimeout 是从 Window 而不是插件对象触发的,并且我希望插件在每个页面上不止一次可用,所以我不能只将当前对象保存到窗口怎么能我做到了?

【问题讨论】:

  • 我认为您对this.moveLeft(); 有疑问?然后使用self(或$this)。
  • 谢谢,但我现在想通了
  • 那么,如果您认为它对其他人有用,请提供您的解决方案作为答案,或者删除您的问题。
  • 我在你评论的时候发布了答案:)

标签: javascript jquery jquery-plugins namespaces


【解决方案1】:

我发现当在return this.each 之外使用this 会给你准确的选择器结果

所以通过一些工作,我设法做到了,

var jScrollerMethods = {
    ready:function(){
        selector = this;

        return this.each(function(){
        var self = this,
    $this = $(this),
        data = $this.data('jScroller');

        settings.timeoutHandle = setTimeout(function(){
            if(settings.direction = "left"){
                selector.jScroller("moveLeft");
            }else if(settings.direction = "right"){
                selector.jScroller("moveRight");
            }
        }, settings.time);

        $this.data('jScroller', {
            settings: settings,
            element: this
        });
    });
}
$.fn.jScroller = function(call){
    if ( jScrollerMethods[call] ) {
      return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof call === 'object' || ! call ) {
        if (call) { $.extend(settings, call); }
        return jScrollerMethods.init.apply( this, call );
    } else {
        $.error( 'Method ' +  call + ' does not exist on jQuery.jScroller' );
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2012-06-08
    • 1970-01-01
    • 2010-10-10
    • 2016-04-17
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多