我决定拥有一个可以在需要插入自定义 Bootstrap 模式时使用的脚本。我不想让空的静态 Bootstrap 模式 HTML 位于每个页面的底部,如果它不总是被利用的话。
所以,这可能是错误的做法,但这是我的尝试。
我创建了一个变量,它是模式“shell”html。然后,当我单击设备项时,它会附加到正文中。然后我克隆了一些内容并将其附加到模式的标题和正文中。一切正常。但模式关闭后我无法将其删除。这与我通过 JS 插入 HTML 的事实有关,因为如果 Modal shell HTML 静态存在于我的 HTML 页面中,则删除工作正常。
HTML:
<ul>
<li class="span4 device">
<div class="inner">
<h3>Device 4</h3>
<div class="device-product">
<img class="device-image" src="img/placeholder-holding-image.png" alt="Holding Image" />
<a href="#" class="hide">Troubleshoot this item</a>
<a href="#" class="hide">How to use this product</a>
</div>
<div class="device-details">
<div class="control-group">
<label class="control-label">Device Type:</label>
<span class="field">Really cool device</span>
</div>
<!-- Small amount of hidden additional information -->
<div class="control-group hide">
<label class="control-label">Device ID:</label>
<span class="field">123456</span>
</div>
</div>
</div>
</li>
</ul>
jQuery:
var customModal = $(
'<div class="custom-modal modal hide fade" tabindex="-1" role="dialog" aria-hidden="true"> \
<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button></div> \
<div class="modal-body"></div> \
<div class="modal-footer"><button class="btn" data-dismiss="modal">Close</button></div> \
</div>'
);
$('.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();
});
所以实际上这只是我正在努力解决的remove() 问题。而且,任何关于我是否以错误/低效的方式处理这件事的评论总是对学习有帮助!
您正在尝试绑定事件处理程序hidden
之前的事件.custom-modal
div 被添加到 DOM,因此事件处理程序永远不会绑定到任何东西。
您可以通过两种方式执行此操作。
-
委托hidden
事件处理程序,以便文档始终监听hidden
源自任何具有自定义模式类的元素的事件:
$(document).on('hidden', '.custom-modal', function () {
$(this).remove();
});
-
将模态 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 更可取,特别是当有可能打开多个模式时。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)