简体   繁体   English

在两个函数之间传递变量

[英]Deliver variable between two functions

I'm using this simple script to create some slider which is starting on mouseenter and which should stops on mouseleave: 我正在使用这个简单的脚本来创建一些从mouseenter开始的滑块,该滑块应该在mouseleave上停止:

$( ".grid-item" ).mouseenter(function() {

  var slides = $(this).find( ".slide-image" ), 
      counter = 0;

  var test = setInterval(function(){
  slides.removeClass('active');
  slides.eq(counter).addClass('active');
  counter++;

  if (counter > slides.length) {counter = 0;};
  }, 600);

}).mouseleave(function() {

  clearInterval(test);
  // $( ".slide-image" ).removeClass('active');

});

The Slider starts quite fine but on the mouseleave-event I'm getting the console error "Uncaught ReferenceError: test is not defined" . 滑块启动得很好,但是在mouseleave事件上,我得到了控制台错误“ Uncaught ReferenceError:未定义测试” I think thats because the variable of the interval is not delivered in the second function. 我认为那是因为间隔的变量未在第二个函数中传递。 Is there any solution? 有什么解决办法吗?

Check out my CodePen! 看看我的CodePen! (It works fine here) (在这里工作正常)

Declare your variable test outside the function 在函数外声明变量test

var test;
$( ".grid-item" ).mouseenter(function() {

  var slides = $(this).find( ".slide-image" ), 
      counter = 0;

  test = setInterval(function(){
  slides.removeClass('active');
  slides.eq(counter).addClass('active');
  counter++;

  if (counter > slides.length) {counter = 0;};
  }, 600);

}).mouseleave(function() {

  clearInterval(test);
  // $( ".slide-image" ).removeClass('active');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM