jquery - Bootstrap 3.3.2 模态事件多次触发

标签 jquery twitter-bootstrap-3

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 &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 timesBootstrap 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 的元素添加一个事件监听器>:

Example Here

$('.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/

相关文章:

javascript - 使用 SASS 进行 Bootstrap

css - Bootstrap LESS 中颜色的默认变量?

html - 外包 css 属性不起作用

jquery - 键盘可操作滑动面板

jquery - 使用 jQuery 生成 iframe 和内容

javascript - 未捕获的 TypeError : (intermediate value). Pie 不是函数 -Chart.js

ajax - 成功的 Ajax 请求后关闭 Bootstrap 模态表单

css - 使列在 Bootstrap 中固定位置

jquery datepicker定位在滚动

javascript - jQuery:在动画期间禁用单击