2012-08-29 114 views
0

我有下面这段代码:删除的事件处理程序的jQuery

jQuery.noConflict(); 
    var x=0; 
    myw=0; 
    oin=""; 
    jQuery(document).ready(function() { 
     if(x >3){ 
      $("img:odd").unbind("mouseenter"); 
      return false; 
     }   
     jQuery("img:odd").mouseenter(function(e) { 
      // oin=""; 
      console.log(e); 
      console.log(this); 
      console.log(this.src); 
      oin=this.src; 
      this.src="snowdrop.png"; 
      myw=this.width; 
      this.width=100; 
      x=x+1; 
      console.log(x); 
      jQuery(this).css("opacity", 0.5); 
     }).mouseout(function(e) { 
      this.width=myw; 
      this.src=oin; 
      jQuery(this).css("opacity", 1.0); 
     }); 


    }); 

的代码运行正常,但我想要做的是后3点鼠标悬停(的mouseenter)我想禁用MouseEnter事件。我无法弄清楚如何解除它?

感谢, 吉姆

回答

1

使用on()off()对于这一点,是这样的:

(function($) { 
    var x=0, 
     myw=0, 
     oin=""; 

    $('img:odd').on({ 
     mouseenter: doStuff, //bind a function, it's easier to rebind 
     mouseleave: function() { 
      this.width=myw; 
      this.src=oin; 
      $(this).css("opacity", 1.0); 
     } 
    }); 


    function doStuff(e) { 
     var elem = e.target; 
     if (x>3) { 
      $(elem).off('mouseenter'); //unbind the event 
      return; 
     }else{ 
      x++; 
      oin=elem.src; 
      elem.src="snowdrop.png"; 
      myw=elem.width; 
      elem.width=100; 
      $(elem).css("opacity", 0.5); 
     } 
    } 
})(jQuery);​ 
+0

我发现这个工作最好。但我也加了$(elem).off('mouseleave');因为即使在mouseenter被删除之后,图像仍在被交换。 –

+0

是的,有时删除这两个处理程序是必要的! – adeneo

+0

这让我开始正确,但我也必须改变所有的引用,例如elem.width = 100 TO this.width = 100 - 原因是没有什么事情发生在上面的代码试图使宽度的图像EVENT 100像素宽。但理论上它是最好的。 –

2

你应该将mouseout事件处理程序

}).mouseout(function(e) { 
     this.width=myw; 
     this.src=oin; 
     jQuery(this).css("opacity", 1.0); 
     if(x == 3){ 
      $("img:odd").unbind("mouseenter"); 
      $("img:odd").unbind("mouseout"); 
     } 
    }); 

也许是更好地做到这一点上的mouseenter处理更加准确里面您解除绑定逻辑

jQuery("img:odd").mouseenter(function(e) { 
     // oin=""; 
     console.log(e); 
     console.log(this); 
     console.log(this.src); 
     oin=this.src; 
     this.src="snowdrop.png"; 
     myw=this.width; 
     this.width=100; 
     x=x+1; 
     console.log(x); 
     jQuery(this).css("opacity", 0.5); 
     if(x == 3){ 
      $("img:odd").unbind("mouseenter"); 
      $("img:odd").unbind("mouseout"); 
     } 
    }) 
0

这个问题完美地回答了这个问题:Best way to remove an event handler in jQuery?

这里有一个例子:

如果你想添加一个事件,然后将其删除(不删除可能已添加的任何其他人),那么你可以使用事件命名空间:

$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ }); 

,并删除只是你的事件:

$('#myimage').unbind('click.mynamespace');