JQuery/Bootstrap:关闭和打开同一个模态刷新内容,动态生成

JQuery/Bootstrap: close and open the same modal to refresh the content, which is generated dynamically

我有一个产品页面,一旦用户点击产品,我就会打开一个动态生成内容的模式。在模态本身中还有其他产品,所以当用户单击那里时,我想关闭模态并重新打开它以刷新内容 - 因此一旦模态重新加载,旧内容应被删除并替换为新内容.

以下简化版:

    <html lang="en">

<head>

<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/ajax.js"></script>

<script>
function openmodal(id){
var id=id;
var other="<a onclick='openmodal(1)' style='cursor:pointer'>product 1</a><a onclick='openmodal(2)' style='cursor:pointer'>product 2</a><a onclick='openmodal(3)' style='cursor:pointer' >product 3</a>";
$('#item_modal').modal('show');
$("#target_title").text(id);
$("#target_other").append(other);
}

</script>

</head>
<body>
<a onclick="openmodal(1)" style="cursor:pointer">product 1</a>
<a onclick="openmodal(2)" style="cursor:pointer">product 2</a>
<a onclick="openmodal(3)" style="cursor:pointer">product 3</a>

<div id="item_modal" class="modal fade" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<h1 id="target_title"></h1>
<div id="target_other">

</div>
</div>

</div>
</div>

<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/classie.js"></script>
<script src="js/cbpAnimatedHeader.js"></script>
</body>
</html>
</body>
</html>

有什么帮助吗? 谢谢 最佳

您可以在下次调用相同模态之前销毁模态对象。隐藏模态时对象被销毁。

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
}); 

DEMO

由于您在同一个实例上隐藏显示,它将再创建一个背景,但无法显示 modal 再一次。因此,您可以在以最小时间间隔显示 modal 之前有一个 setTimeout 这将是低效的,因为背景不会被破坏 或者只是利用shown.bs.modal 方法并隐藏 modal,然后显示如下:

function openmodal(id){
    var id=id;
    //No need to hide here
    $('#item_modal').modal('show');
    $("#target_title").text(id);
}

$("#item_modal").on("shown.bs.modal",function(){
   //will be executed everytime #item_modal is shown
   $(this).hide().show(); //hide first and then show here
});

更新

这里有一个 fadeInfadeOut 的效果是一个小技巧,但你可能会觉得它有点 slow 并且是否选择这个解决方案取决于你

DEMO

function openmodal(id){
    var id=id;
    var other="<a onclick='openmodal(1)' style='cursor:pointer'>product 1</a><a onclick='openmodal(2)' style='cursor:pointer'>product 2</a><a onclick='openmodal(3)' style='cursor:pointer' >product 3</a>";
    $('#item_modal').fadeOut("slow",function(){
        $(this).modal('hide')
    }).fadeIn("slow",function(){
        $("#target_title").text(id);
        $("#target_other").html(other);
        $(this).modal('show')
    });
}

您现在可以删除 shown.bs.modal 部分,因为它是在 function 本身中处理的