如果点击里面的按钮,关闭模态

Close modal if a button inside is clicked

本文关键字:模态 按钮 如果      更新时间:2023-09-26

我想做的是在bootstrap的模态对话框的帮助下进行单页表单切换。

我的问题是当我在模态对话框中单击按钮时,模态对话框不会关闭,但表单开关成功切换…有没有人知道如何使模态对话框关闭,如果我点击了模态中的任何按钮?

模式对话框的HTML:

<a data-toggle="modal" href="#myModal">Click me</a></li>
<div class="container">
  <div class="row">
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog">
       <div class="modal-content">
         <div class="modal-body">
           <form class="form-horizontal">
             <div class="form-group">
               <div class="col-sm-offset-2 col-sm-10">
                 <button type="button" id="show_first" class="btn btn-primary" data-dismiss="modal" aria-hidden="true">First</button>
                 <button type="button" id="show_second" class="btn btn-info" data-dismiss="modal" aria-hidden="true">Second</button>
               </div>
             </div>
           </form>
          </div>
       </div>
     </div>
   </div>
 </div>
</div>
<div class="container">
  <div class="myFirst">
    <div class="row">
      <center>
        <h1>First Page</h1>
      </center>
    </div>
  </div>
  <div class="mySecond">
    <div class="row">
      <center>
        <h1>Second Page</h1>
      </center>
    </div>
  </div>        
</div>

脚本:

<script type="text/javascript">
    $(function(){
        $('.myFirst').hide();
        $('.mySecond').hide();
        $('#show_first').click(function(){
            $('.mySecond').hide();
            $('.myFirst').show();
            return false;
        });
        $('#show_second').click(function(){
            $('.myFirst').hide();
            $('.mySecond').show();
                return false;
        });
    });
</script>

正如评论中所说,在bootstrap中,你可以调用.modal('hide')来关闭你的模态窗口,所以你可以像这样添加它到你绑定的点击事件中:

$('#show_first').click(function(){
    $('.mySecond').hide();
    $('.myFirst').show();
    $('.modal').modal('hide');
    return false;
});
$('#show_second').click(function(){
    $('.myFirst').hide();
    $('.mySecond').show();
    $('.modal').modal('hide');
    return false;
});