【发布时间】:2015-05-17 05:06:05
【问题描述】:
Bootstrap Modal Events 触发多次,或者更确切地说总是比之前多一次。我将模态事件包装在一个 click 函数中,该函数现在返回模态 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,如果有人真的有一本好的书,甚至是唯一一本的书来阅读这方面的内容,那么请给我留个便条,那里有这么多,而且都声称自然是最好的..谢谢。)
【问题讨论】:
-
在我的例子中,不得不放“.off()”,因为相同的模态是从不同的地方加载的。感谢您的回答!
标签: jquery twitter-bootstrap-3