2012-08-29 112 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');