在内部模式元素上在.show()上触发事件show.bs.modal

时间:2018-06-22 21:34:24

标签: javascript event-handling bootstrap-4 bootstrap-modal formvalidation.io

我刚刚意识到,不仅在显示模态本身时,而且在每次为模态内的元素调用.show()方法时,都不会触发show.bs.modal事件。

事件处理程序的附加方式如下:

$('#modalName').on('show.bs.modal', function(event) { ... });

关于如何确保仅在模式显示中触发此处理程序中的代码的任何想法?

尤其是如果您在模式中使用formValidator.io(一旦对表单字段的验证不成功,就会对元素调用.show()),就会出现问题

1 个答案:

答案 0 :(得分:0)

有一种解决方法-检查event.relatedTarget所谓的.show(),如果无意中调用了该代码,则停止运行代码-例如:

$('#modalName').on('show.bs.modal', function(event) {    
    if (!$(event.relatedTarget).parents(this).length) // checks if event has been executed by running .show() from outside the modal
        return false; // this will terminate and rest of the code will not be executed
    ... // other things you need to do on the event handler
});

但是,这只是解决方法-任何其他建议,这些建议会使该解决方案更加优雅。