Bootstrap 3.3.2 模态事件多次触发

Bootstrap 3.3.2 Modal events fire multiple times

Bootstrap Modal Events 触发多次,或者说总是比之前多触发一次。我将模态事件包装在点击函数中,returns 现在是模态 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 &times;</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,您都会为 [=13] 附加 一个新的 事件侦听器=] 事件。这就是每次点击都会触发事件 show.bs.modal 的原因。

Can someone please explain to me why this .off method is needed in this case exactly?

.off() 方法只是删除之前附加的事件。


您不需要使用 .off() 方法。

与其在每个点击事件上为事件 show.bs.modal 附加一个事件侦听器,不如为具有 class .modal:[=28 的所有元素添加一个事件侦听器=]

Example Here

$('.modal').on('show.bs.modal', function (event) {
    console.log(this.id);
});

show.bs.modal 事件侦听器中,this 绑定到显示的 .modal 元素;因此您可以确定显示的是哪个模态。在上面的示例中,this.id 将是 modal-1.

modal.off().on('show.bs.modal', function(){
    modalBody.load(remote_content);
});

就我而言,我面临多个 remote_loads。 '.off()' 帮助我将之前绑定的事件解除绑定到目标模式。