如何删除通过jQuery插入的bootstrap模式?

我决定如果需要插入自定义Bootstrap模式,我想要一个可以使用的脚本。 我不想让每个页面底部都有空的静态Bootstrap模态HTML,如果不能总是使用它的话。

所以,这可能是错误的做法,但这是我的尝试。 我创建了一个变量,它是模态’shell’html。 然后,当我单击一个设备项时,它将附加到正文。 我有一些内容然后克隆并附加到模式的标题和正文。 一切正常。 但一旦关闭,我无法移除模态。 这与我通过JS插入HTML这一事实有关,因为如果Modal shell HTML在我的HTML页面中静态存在,则删除工作正常。

HTML:

 

jQuery的:

 var customModal = $( '' ); $('.device').click(function(){ $('body').append(customModal); $(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(); }); $('.custom-modal').on('hidden', function(){ $(this).remove(); }); 

所以真的只是我正在努力的删除()。 但是,任何关于我是否以错误/低效的方式解决这个问题的评论总是有助于学习!

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

你可以这两种方式。

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

     $(document).on('hidden', '.custom-modal', function () { $(this).remove(); }); 
  2. 在将模态div添加到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是首选,特别是如果有可能打开多个模态。