Close bootstrap modal without using “hide” and “data-dismiss”

烂漫一生 提交于 2019-11-27 13:53:15

问题


I want to close bootstrap modal box conditionally. If I use $('#modal').modal('hide'); this, some thing goes wrong with my code. And If I use data-dismiss="modal" in the HTML template, modal dismiss action performs before my actual functionality should be perform on button click.

So, there is any other way to close bootstrap modal or any idea to use data-dismiss="modal" at run time?


回答1:


You can do it with auto modal closing behavior which uses the data-dismiss attribute itself or with the manual modal opening (as i guess you are doing currently) , by subscribing to hide event and use preventDefault on the event.

$('yourmodalselector').on('hide',function(e){
   if(yourConditionNotToCloseMet){
      e.preventDefault();
   }
});

Demo

Demo2

See Documentation

hide event event is fired immediately when the hide instance method has been called, which gets called wither way and this is the best place to prevent the modal from closing.




回答2:


Make another button like this

<button type="button" class="btn btn-warning btn-lg shiny" data-dismiss="modal" aria-hidden="true">Cancel</button>

This button contains data-dismiss="modal" .You can hide this if you want.

Now You can use any other function in a customized way and when you want to hide the modal you can call

$(".btn-warning").click();


来源:https://stackoverflow.com/questions/16972809/close-bootstrap-modal-without-using-hide-and-data-dismiss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!