情况是在我单击将显示模态的按钮后,它将运行一个内部包含 2 个 jquery 的单击事件:
- .html 到 modal-body 类
- ('show.bs.modal') 事件包含 .append 到 modal-body 类
HTML(按钮)
<button class="btn btn-default view_detail" data-toggle = "modal" data-target="#transactionDetailModal">Detail</button>
相同的 HTML(模态)
<!-- Modal -->
<div class="modal fade" id="transactionDetailModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Selling Report</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').append('<p>.append element</p>');
});
});
});
发生的事情是,如果我单击一次按钮,它似乎工作正常(这是我想要的结果):
但是在第一次点击之后,附加元素继续出现,尽管我认为它会被 .html 覆盖
而且还在不断增加
我想要的是 .append 每次点击模态按钮时都会被覆盖(就像第一次点击图片一样)。如果我将 .append 放在 ('show.bs.modal') 之外,它将运行正常,而不会在每次单击按钮时一遍又一遍地显示先前附加的元素.
JS
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
//I moved this one out from show bs modal below
$('.modal-body').append('<p>.append element</p>');
$('#transactionDetailModal').on('show.bs.modal', function (event) {
});
});
});
上面的JS代码修复了不断出现追加元素的问题。
但为什么会这样呢?我认为附加元素肯定会被覆盖,因为每次我单击按钮时它都会运行 .html,这意味着 modal-body 类中的所有元素都将被覆盖。
最佳答案
('show.bs.modal') 每次显示模式时都会触发事件。您之前编写的函数(如下所示)将在每次显示模态时单独执行,并且 html 函数覆盖单独编写代码。
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').append('<p>.append element</p>');
});
此函数将单独触发,而不是在单击 ('.view_detail') 按钮时触发。
可以删除 ('show.bs.modal') 事件。
$(document).ready(function(){
$('.view_detail').on('click',function(event){
$('.modal-body').html('<p>.html element</p>');
$('.modal-body').append('<p>.append element</p>');
});
});
});
或者您可以在单个函数中触发它,如下所示:
$(document).ready(function(){
$('#transactionDetailModal').on('show.bs.modal', function (event) {
$('.modal-body').html('<p>.html element</p>');
$('.modal-body').append('<p>.append element</p>');
});
});
使用任何一个函数来消除问题。
关于javascript - show.bs.modal 中的附加元素未在 Bootstrap Modal 中被 .html 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240951/