Javascript 如何将“Flexslider”当前图像编号放入我可以在函数中使用的变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11215364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:57:07  来源:igfitidea点击:

How do I get the 'Flexslider' current image number into a variable which I can use in a function?

javascriptjqueryflexslider

提问by byronyasgur

I am using flexslider. There is an example under the advanced tap on thispage (in the section "The new, robust Callback API"where they use slider.currentSlideto get the number of the current slide.

我正在使用flexslider。在页面上的高级点击下有一个示例(在“新的、强大的回调 API”部分中,它们用于slider.currentSlide获取当前幻灯片的编号。

How can I access this value in a completely different function? I am thinking of a global variable but I don't know if that will work and I don't know if it's possible to declare a variable within a function as global.

如何在一个完全不同的函数中访问这个值?我正在考虑一个全局变量,但我不知道这是否可行,我不知道是否可以将函数中的变量声明为全局变量。

回答by Lewis

You can avoid global variables by accessing the flexslider object with:

您可以通过访问 flexslider 对象来避免全局变量:

$(element).data('flexslider')

So in your case you'd use:

所以在你的情况下,你会使用:

$(element).data('flexslider').currentSlide

回答by riku

You can declare a global variable and set the value in the after callback function. Here's some pseudocode to help you get the idea:

您可以声明一个全局变量并在之后的回调函数中设置值。这里有一些伪代码可以帮助你理解:

var curSlide;
$(window).load(function() {
  $('.flexslider').flexslider({
    after: function(slider) {
      window.curSlide = slider.currentSlide;
    }
  });
});

function useCurSlideHere() {
  alert(window.curSlide);
}

Although ideally you'd avoid using a global variable and you could make the useCurSlideHere function into a class which you create an instance of on window.load and use it when you pass the curSlide variable in the after callback function.

尽管理想情况下您会避免使用全局变量,并且您可以将 useCurSlideHere 函数放入一个类中,您可以在该类中创建 on window.load 的实例,并在后回调函数中传递 curSlide 变量时使用它。

$(window).load(function() {
  var customSlider = new useCurSlideHere();
  $('.flexslider').flexslider({
    after: function(slider) {
      customSlider.setCurSlide(slider.currentSlide);
    }
  });      
});

function useCurSlideHere() {
  this.curSlide = 0;

  this.setCurSlide = function(curSlide) {
    this.curSlide = curSlide;
  }

  this.getCurSlide= function() {
    alert(this.curSlide);
  }
}

EDIT: Edited the answer to use slider.currentSlide.

编辑:编辑答案以使用slider.currentSlide。