为什么 jQuery replaceWith 元素克隆不适用于 Twitter BootStrap 模态?



我有一个引导模式,其主体包含一个 span 元素。单击链接时,该链接的数据用户名属性将插入到模式内的 span 元素中,并显示模式。单击继续按钮时,状态消息将插入到模式正文中。单击"关闭"按钮时,模式将关闭,但模式需要返回到加载页面时的原始状态。这是我到目前为止所拥有的:

<a href="#" data-username="Olivia Benson"><i class="fa fa-plus"></i></a>
<a href="#" data-username="Elliot Stabler"><i class="fa fa-plus"></i></a>
<a href="#" data-username="John Munch"><i class="fa fa-plus"></i></a>
<div class="modal fade" id="userAccess" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Grant Access to <?php echo get_the_title($_GET['id']);?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>You are about to grant <span id="userDisplayName"></span> access to manage <span><?php echo get_the_title($_GET['id']);?>.</span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="proceed">Proceed</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal" id="close">Close</button>
</div>
</div>
</div>
</div>
(function($){
$modalClone = $('.modal#userAccess').clone();
$('#userAccess').on('hide.bs.modal', function(){
$('.modal#userAccess').replaceWith($modalClone);
});
$('a[data-username']').on('click', function(e){
$username = $(this).attr('data-username');
$('.modal#userAccess span#userDisplayName').html($username);
$('.modal #userAccess #close').on('click', function(){
$('.modal#userAccess').modal('hide')
$('#proceed').on('click', function(){
$('.modal#userAccess .modal-body').html(
$('<p></p>').html("You have granted "+$username+" access.")
});
e.preventDefault();
});
})(jQuery);

问题是模态永远不会被原始模态的克隆所取代。我做错了什么?控制台中没有错误。

这是一个 jsFiddle 来演示。单击链接。单击继续。模态主体的内容将发生变化。然后关闭模式并单击其他链接。首次单击继续按钮时插入的状态消息仍将存在。它应该显示您第一次打开模态时显示的消息,但它没有。这些过程可能在您第一次完成它们时有效,但之后它们将不起作用。

你在这里有两个问题。首先,当您侦听hide.bs.modal时,您的目标是当时 DOM 上的模态。但是后来你用它替换了克隆,这个侦听器不知道新添加的模态。要解决这个问题,你需要监听文档,因为它是静态的,事件最终会冒泡到它。第二个问题是你只有一个克隆,用那个克隆替换旧的克隆后,你没有新的克隆,而是替换相同的元素。这就是为什么在替换时需要克隆克隆的元素本身。这样,您将始终拥有新鲜的模态实例。

(function($){
$modalClone = $('.modal#userAccess').clone();
$(document).on('hide.bs.modal', '.modal#userAccess', function(){ // here 
console.log($modalClone.clone())
$('#userAccess').replaceWith($modalClone.clone()); // and here
});
$('a[data-username]').on('click', function(e){
$username = $(this).attr('data-username');    
$('.modal#userAccess span#userDisplayName').html($username);
$('#userAccess').modal('show')
$('.modal #userAccess #close').on('click', function(){
$('.modal#userAccess').modal('hide')
});
$('#proceed').on('click', function(){
$('.modal#userAccess .modal-body').html(
$('<p></p>').html("You have granted "+$username+" access.")
)
$(this).remove()
})
e.preventDefault();
});
})(jQuery);

最新更新