jQuery — 通过根据用户活动变化的变量更新函数的初始参数?



我不明白如何更新一个函数的初始参数,一旦他们已经设置。

我使用一个名为serialScroll的插件。插件滚动到初始$(elem). serialscroll({//…})设置中指定的项。

我想做的是在用户与页面交互时重新定义该项的名称。我还有另一个变量,它在用户滚动时成功地收集信息,我有这么多。

所有我想做的是使serialScroll({)}更新它的"item:_"字段相应的变量。

下面是serialScroll代码:

    var nextClass = ".fig4"; 
    // this is being changed to .figN depending on the users 
    // scrolling position in the browser/viewport (successfully). 
    // For proof of communication purposes I forced nextClass 
    // here to equal .fig4 to see if the two are at lest talking to 
    // each other, which they are... but now how do i update "items:" 
    // below to reflect the change in the "nextClass" variable?
$('html').serialScroll({
    target:'body',
    items: nextClass, 
    next:'#nextImage',
    axis:'y',
    duration:700,
    force:true, 
});

这里发生的事情是,当. serialscroll初始化时,它获得nextClass的值一次,这是它使用的值。

必须发生两件事中的一件。您可以修改插件以使用全局变量(不是非常理想,但它可以工作),或者每次nextClass更改时,都需要重新初始化. serialscroll .

JavaScript对象是动态的,你总是可以给它们添加方法。由于serialScroll是一组动态添加到被调用元素的函数,因此有两种方法可以完成所需的功能:

  1. 在插件代码中添加一个setter -这将使它在所有安装中工作
  2. monkey-在初始化
  3. 后修补每个serialScroll实例

如果您只有一个实例,那么后者更容易,并且应该被证明是更向前兼容的:

$('html').serialScroll({...});
$('html').serialScroll.setItems = function(i){
  items = i;
}
// when nextClass changes
$('html').serialScroll.setItems(nextClass);

要完成第一个选项,需要侵入serialScroll代码本身。

最新更新