<!--data-backdrop禁止点击空白处关闭模态框,也可以js设置,其他参数可参考官网模态框文档--> <div class="modal fade" id="modal" data-backdrop="static"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span>×</span></button> <h4 class="modal-title" id="modalTitle">新增数据</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="recipient-name" class="control-label">Recipient:</label> <input type="text" class="form-control" id="recipient-name"> </div> <div class="form-group"> <label for="message-text" class="control-label">Message:</label> <textarea class="form-control" id="message-text"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">放弃操作</button> <button type="button" class="btn btn-primary">确认提交</button> </div> </div> </div> </div>
<!-- data-toggle配置此按钮为模态框开关,data-target配置目标模态框,data-mydata传递给模态框回调事件的自定义属性值 --> <button id="addDataBtn" class="btn btn-info col-md-1" type="button" data-toggle="modal" data-target="#modal" data-mydata="abc"> <span class="glyphicon glyphicon-plus"></span> 新增数据 </button>
/*绑定触发模态框show函数立即执行的回调事件*/ $('#modal').on('show.bs.modal', function (event) { console.log('run..'); //触发模态框的按钮 var button = $(event.relatedTarget) // Button that triggered the modal console.log(button); var recipient = button.data('mydata') // Extract info from data-* attributes var modal = $(this) // modal.find('.modal-title').text('New message to ' + recipient) // modal.find('.modal-body input').val(recipient) console.log(recipient); })
虽然js也可以操纵bootstrap模态框,但看过官网文档后明显提供的方法不足,例如向模态框内传递数据。建议还是使用html来操纵模态框。