2011-10-25 47 views
1

我正在製作自己的燈箱,關閉燈箱並再次打開後出現問題。jQuery函數重複

下面是簡單的函數代碼

(function($) { 
    $.fn.lghtbx = function() { 
     var lghtbxLink = $(this); 
     lghtbxLink.click(function() { 
      $('body').append("<div id=\"ZoomGallery\"></div>"); 
      $('#ZoomGallery').css({'width': '100%','height': '100%', 'position': 'absolute', 'left': '0px', 'top': '0px', 'backgroundColor':'#000'}); 

      $('#ZoomGallery').live('click',function() { 
       $('#ZoomGallery').remove(); 
      }) 

      $(document).keydown(function(event) { 
       switch (event.keyCode) { 
        case 37://left 
        alert('left!'); 
        break; 
       } 
      }) 
     }) 
    } 
})(jQuery); 

我打電話這樣

$(document).ready(function() { 
    $('.lightbox').lghtbx(); 
}); 

該功能,這是簡單的HTML

<a class="lightbox" href="#">a</a> 

當我點擊鏈接並按鍵盤上的向左箭頭警告出現。這就是它應該如何工作。但是當我通過點擊黑色的div來關閉燈箱並且當我通過點擊鏈接再次打開燈箱時,問題就會彈出。每次我點擊左箭頭,我都會收到兩次警報。如果我再次關閉並打開燈箱並按下左箭頭,我會收到三次警報......等等。

你能幫我解決這個問題嗎?

+0

您需要解除綁定的keydown –

回答

2

首先刪除舊事件

$(document).unbind("keydown").keydown(function(event) { 
+0

沒有,這樣的keydown事件仍然存在,即使沒有收藏。 –

+0

在這裏試試http://jsfiddle.net/ASS4D/1/:關閉燈箱並按左邊 –

1

這是監守你,曾多次結合的盛會。

 $('#ZoomGallery').live('click',function() { 
      $('#ZoomGallery').remove(); 
      $(document).unbind("keydown"); 
     }) 

小提琴這裏:當您關閉燈箱您應該取消綁定事件http://jsfiddle.net/ASS4D/