我决定编写一个脚本,以便在需要插入自定义Bootstrap模态框时使用。如果不总是使用它,我不想在每个页面底部放置空的静态Bootstrap模态框HTML。
因此,这可能不是正确的方法,但这是我的尝试。 我创建了一个变量,它是模态框的“外壳”HTML。然后,当我单击设备项时,它将附加到主体中。我还克隆并附加了一些内容到模态框的标题和正文。一切都正常工作。但是,一旦关闭模态框,我就无法将其删除。这与我通过JS插入HTML有关,如果模态框外壳HTML静态存在于我的HTML页面中,则删除功能正常。
HTML:
因此,这可能不是正确的方法,但这是我的尝试。 我创建了一个变量,它是模态框的“外壳”HTML。然后,当我单击设备项时,它将附加到主体中。我还克隆并附加了一些内容到模态框的标题和正文。一切都正常工作。但是,一旦关闭模态框,我就无法将其删除。这与我通过JS插入HTML有关,如果模态框外壳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()。但是,关于我是否以错误/低效的方式进行操作的任何评论都有助于学习!
.custom-modal
div,但我有一个单独的问题,当模态框再次触发时,它仍然包含来自上一个触发的附加内容。 - davidpauljunior$(document).on('hidden', '.modal', function () { $(this).removeData('modal'); });
但是没有用。JSFiddle在这里:http://jsfiddle.net/davidpauljunior/rMyMy/ - davidpauljuniorcustomModal
包装为 jQuery 对象。改为传递字符串。例如,customModal = '<div class=...' 当你将其转换为 jQuery 对象后,即使在将其从 DOM 中移除后,它仍然存在并继续接收修改。 - thefrontender$(document).on('hidden.bs.modal', '.custom-modal', function () { $(this).remove(); });
该代码的作用是在模态框隐藏后将其从DOM中移除。 - jyoseph