Bootstrap Modal Events多次开火,或者更确切地说,总是比以前多开火一次。我将模态事件包装在一个点击函数中,该函数现在返回模态 ID。
如何确保事件始终仅触发一次,并且仅在单击函数调用它时触发?
jQuery
$('.img-modal').on('click', function () {
// returns #modal-Id
var modalIdClicked = $(this).attr('data-target')
console.log ('modal id clicked from .img-modal = '+ modalIdClicked);
console.log ('.img-modal clicked');
$(modalIdClicked).on('show.bs.modal', function(event) {
console.log ( 'show.bs.modal');
});
});
默认 Bootstrap 3.3.2 模态 HTML
<div class="col-md-7">
<img class="img-modal img-responsive cursor-pointer" data-toggle="modal" data-target="#modal-1" src="www" alt="image">
</div>
<!-- Modal -->
<div class="modal fade top-space-0" id="modal-1" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content cursor-pointer" data-toggle="modal" data-target="#modal-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="#modal-1">CLOSE ×</button>
<h1 class="modal-title">Modal Title</h1>
</div>
<div class="modal-body">
<div class="img-center">
<img class="img-modal img-responsive" src="wwww" alt="image">
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-default" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
<!-- Modal end -->
我确实看过jQuery click events firing multiple times和
Bootstrap 3 - Remotely loaded modal creates duplicate javascript events看来这可以通过 .off
方法来实现。
因此,在这种情况下使用 $(modalIdClicked).off().on('show.bs.modal', function(event) {
就达到了目的。
有人可以向我解释一下为什么在这种情况下需要这个.off
方法吗?我无法理解点击是如何传递的。
每次点击都会再次到达 Bootstrap JS 吗?为什么它会在没有 .off
方法的情况下多次触发事件?
谢谢。
(我正在尝试从一本书中学习 jQuery,如果有人真的有一本好书,甚至唯一一本书来阅读这方面的内容,那么请给我留言,那里有很多并且都声称自然是最好的..谢谢。)
最佳答案
Why does it fire the events multiple times without the
.off
method?
因为每次单击元素 .img-modal
时,您都会为 show 附加一个新的事件监听器。 bs.modal
事件。这就是为什么每次点击都会再次触发 show.bs.modal
事件。
Can someone please explain to me why this
.off
method is needed in this case exactly?
.off()
方法只是删除之前附加的事件。
您不需要使用 .off()
方法。
您不应为每个点击事件上的 show.bs.modal
事件附加一个事件监听器,而应该为所有具有类 .modal
的元素添加一个事件监听器>:
$('.modal').on('show.bs.modal', function (event) {
console.log(this.id);
});
在 show.bs.modal
事件监听器中,this
绑定(bind)到显示的 .modal
元素;因此您可以识别显示哪个模式。在上面的示例中,this.id
将是 modal-1
。
关于jquery - Bootstrap 3.3.2 模态事件多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053874/