开发者

accessing multiple instances in jquery

开发者 https://www.devze.com 2023-02-09 00:28 出处:网络
so i have a page of products, and for each one i want to cycle through some images on mouseover, and have it stop on mouseout.the following code is my current state...

so i have a page of products, and for each one i want to cycle through some images on mouseover, and have it stop on mouseout. the following code is my current state...

initially i had it working where it checked a global variable called repeatCycle to see if it should rotate to the next image. this caused problems because all the instances of this function were checking & setting the same variable. i would often get multiple instances running at once. so i want to set something for each instance instead, but was not able to do it.

i also tried passing it in as an argument to the function, but on the mouseout event when i passed in repeatCycle: false, it would just initialize another instance.

anyone have any suggestions as to how to accomplish this?

$.fn.image_cycler = function(options){
  // default configuration properties
  var defaults = {
    fade_delay: 开发者_如何学JAVA    150,
    image_duration: 1500,
  };
  var options = $.extend(defaults, options);

  this.each(function(){
    var product     = $(this);
    var image       = $('div.image>a.product_link>img', product);
    var description = $('div.image>div.description', product);
    var all_images  = $('div.all_images', product);
    var next_image  = ($(all_images).find('img[src="' + $(image).attr('src') + '"]').next('img').attr('src')) ? $(all_images).find('img[src="' + $(image).attr('src') + '"]').next('img') : $(all_images).children('img').first();;

    // mouseover
    image.fadeOut(options.fade_delay, function(){
      image.attr('src', next_image.attr('src'));
      image.fadeIn(options.fade_delay);
    });
    if (this.repeatCycle){
      var loop = function() {
        return this.image_cycler(options);
      }
      setTimeout(loop,options.image_duration);
    }
  });
};

$(document).ready(function() {
  $('div.product').hover(function(){
    $(this).image_cycler();
  }, function(){
    $(this).image_cycler.repeatCycle = false;
  });
});


Try using jQuery's .data(). e.g. something like replacing the lines:

if (this.repeatCycle){ 
....
$(this).image_cycler.repeatCycle = false;

by:

if (product.data('repeatCycle')){
....
$(this).data('repeatCycle', false);
0

精彩评论

暂无评论...
验证码 换一张
取 消