Function jQuery函数重复执行

Function jQuery函数重复执行,function,lightbox,jquery,Function,Lightbox,Jquery,我正在制作自己的灯箱,在关闭灯箱并再次打开后出现问题 下面是简单的函数代码 (function($) { $.fn.lghtbx = function() { var lghtbxLink = $(this); lghtbxLink.click(function() { $('body').append("<div id=\"ZoomGallery\"></div>"); $('#Zo

我正在制作自己的灯箱,在关闭灯箱并再次打开后出现问题

下面是简单的函数代码

(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);
这就是简单的html

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

当我点击链接并按下键盘上的左箭头时,会出现警告。这就是它的工作原理。但是当我通过点击黑色div来关闭灯箱,当我通过点击链接再次打开灯箱时,问题就出现了。每次单击左箭头,我都会得到两次警告。如果我再次关闭并打开lightbox并按下左箭头,我将获得三次警报。。。等等


您能帮我解决这个问题吗?

首先删除旧事件

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

这是因为您绑定事件的次数不止一次。关闭灯箱时应解除事件绑定:

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

在此处拨弄:

否,这样即使没有灯箱,按键向下事件仍然存在。您需要解除按键向下的绑定
        $('#ZoomGallery').live('click',function() {
            $('#ZoomGallery').remove();
            $(document).unbind("keydown");
        })