且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除通过jQuery插入的引导程序模式?

更新时间:2023-12-03 13:23:46

您正在尝试将.custom-modal div添加到DOM之前为hidden事件绑定事件处理程序,因此永远不要使用事件处理程序.绑定到任何东西.

You're attempting to bind the event handler for the hidden event before the .custom-modal div is added to the DOM, so the event handler is never bound to anything.

您可以通过两种方式做到这一点.

You can do this two ways.

  1. 委托hidden事件处理程序,以便文档始终侦听源自具有自定义模式类的任何元素的hidden事件:

  1. Delegate the hidden event handler so that the document is always listening for hidden events originating from any element with a class of custom-modal:

$(document).on('hidden', '.custom-modal', function () {
    $(this).remove();
});

  • 将模式div添加到DOM后,绑定事件处理程序:

  • Bind the event handler after you've added the modal div to the DOM:

    $('.device').click(function(){
        // Push the modal markup into the DOM
        $('body').append(customModal);
    
        // Now that it's in the DOM we can find it and bind an event handler
        $('.custom-modal').on('hidden', function () {
            $(this).remove();
        });
    
        // Continue with other init tasks
        $(this).find('h3').clone().appendTo('.custom-modal .modal-header');
        $(this).find('.device-product, .device-details').clone().appendTo('.custom-modal .modal-body');
        $('.custom-modal.hide').show();
        $('.custom-modal').modal();
    });
    

  • 选项1是可取的,特别是如果有可能会打开多个模态的话.

    Option 1 is preferable, especially if there's a chance that multiple modals will be opened.