如何在jQuery方法中包含javascript变量?

时间:2012-05-18 23:51:59

标签: jquery

auto-pagination无限滚动脚本有一个名为offset的变量。我想将它传递给scrollPagination方法(当它再次被调用时),但我不知道该怎么做。

我需要执行此操作,因为offset部分内的afterLoad变量发生变化,而offset参数的contentPage始终为0。

var offset = 0;
$('#stuffhere').scrollPagination({ 
    'contentPage': 'themes/[var.theme]/ajaxcontrols.php?page=products&offset='+offset, // the page where you are searching for results
    },
    'afterLoad': function(elementsLoaded, offset){ // after loading, some function to animate results and hide a preloader div
         offset = offset + [var.homelist]; alert(offset);
    }
});

修剪代码示例。

更新

这是我得到的结果。 offset is still zero

知道变量范围。我想将变量offset传递给.scrollPagination({而不知道该怎么做。使用.scrollPagination function(offset){不起作用。

2 个答案:

答案 0 :(得分:4)

更好的是...在加载之前使用,删除原始的contentPage字符串。否则搜索通常会重复。例如:

    'beforeLoad': function(){ // before load function, you can display a preloader div
        $('#loading').fadeIn();         
         offset += 10;  
         this.contentPage = "democontent.php?offset=" + offset;
    },

更新

你知道,我认为在这种情况下实际上有一个更简单的解决方案,不需要黑客攻击插件甚至是monkeypatching它:

// Inside afterLoad

offset += 8;

this.contentPage = "..." + offset;

我刚注意到afterLoad被称为opts.afterLoad,在这种情况下应该将this绑定到函数内的opts

原始答案

好吧,在我看来,您最初传递给ScrollPagination插件的网址用于每个请求,并且不会在外部公开,以便您在请求之间进行更改(例如在afterLoad中)。你可以破解插件以允许它,或者使用新的loadContent()进行monkeypatch,例如:

var offset = 0;

var loadContent = $.fn.scrollPagination.loadContent;

$.fn.scrollPagination.loadContent = function ( obj, opts ) {

  opts.contentPage = 'themes/jessicatheme/ajaxcontrols.php?page=products&offset=' + offset;

  return loadContent.call( this, obj, opts );

};


$( '#stuffhere' ).scrollPagination({

...

我想联系插件作者,看看他们是否会在MIT或Simplified BSD许可下发布它,以便可以修改和分发。

答案 1 :(得分:1)

使用JavaScript闭包,您不需要明确地传递它。函数定义时范围内的变量将在该函数闭包中并且可以被引用。如果你想了解更多关于闭包的信息(它们并不像你想象的那么复杂),请阅读这篇文章。这非常好:How do JavaScript closures work?

var offset = 0;
$('#stuffhere').scrollPagination({ 
  'contentPage': 'themes/[var.theme]/ajaxcontrols.php?page=products&offset='+offset,
  }
  ,'afterLoad': function(elementsLoaded){ 
     // offset will reference to the variable in the beginning of this script. It will be shared by all afterLoad invokes. Not sure if that is what you want
     offset = offset + [var.homelist];
     alert(offset);
  }
});